Since you just want to sort the books, there is conceptually no need to use a Map as the target data structure. A SortedSet
or even a List
seems a more appropriate type. Here is a skeleton 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 (e.g. descending by book title), define alternative comparator classes and populate a different treeset.
(If you were sorting a really large hashmap of books, it might be more efficient to use an ArrayList and quicksort rather than TreeSet and tree insertion sort. But for any book collection small enough that you would contemplate displaying on the screen it, sorting efficiency is not a concern.)