Sorting collection of objects in HashMap based on object variable
I have a collection of book objects in a HashMap. The book has book_title, book_author, book_year_published, etc. I want to sort them based on book_title, which is a string, in both ascending and descending order, and display them on the screen.
I wish someone could help me - I did it for hours and still didn't have a solution. Thanks in advance.
a source to share
Since you just want to sort the books, conceptually there is no need to use a map as the target data structure. A, SortedSet
or even List
appears to be a more appropriate type. Here's a skeletal solution:
class Book {
public String getTitle() {
....
}
...
}
class AscendingTitle implements Comparator<Book> {
public int compare(Book b1, Book b2) {
return b1.getTitle().compareTo(b2.getTitle());
}
}
...
SortedSet<Book> orderedBooks = new TreeSet<Book>(new AscendingTitle());
orderedBooks.addAll(hashMap.valueSet()); // or hashMap.keySet();
...
To sort in different orders (for example, descending by book title), define alternative comparator classes and populate another treeet.
(If you were sorting a really large hash file of books, it might be more efficient to use ArrayList and quicksort sorting rather than TreeSet and tree sorting. But for any collection of books small enough to display on screen, sorting efficiency is not is troubling.)
a source to share
Use TreeMap
with custom Comparator
:
sortedMap = new TreeMap (bookTitleComparator); sortedMap.putAll(bookMap);
gives you a sorted version of your HashMap
.
To reverse the order use
revComparator = Collections.reverseOrder (bookTitleComparator);
(see docs )
a source to share