views:

167

answers:

2

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 the book_title which is a String, in both ascending and descending order, and display them on the screen.

I wish someone can help me - I have been doing this for hours and still havent come up with a solution. Thanks in advance.

+2  A: 

Use a TreeMap with a 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 the docs)

Aaron Digulla
There is no such constructor; see http://java.sun.com/javase/6/docs/api/java/util/TreeMap.html
Stephen C
+1 for the general idea of "Use a TreeMap with a custom Comparator". (Took the liberty to fix broken example code.)
Jonik
+3  A: 

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.)

Stephen C
+1, probably more useful than going with TreeMap (which I only realised now after reading the *whole* question :P)
Jonik
thank you for the help, but i still dont get which part of the code determines whether the result is in ascending or descending?
chandra wibowo
the "compareTo" bit. You could swap the arguments around to sort it the other way.
Adrian Mouat
@chandra: Stephen's answer just gives you an example for how to do the **ascending** case. Based on the example, it should be straightforward to create your own "DescendingTitle" Comparator and use it in the exact same way as above.
Jonik
@Adrian - I was going to suggest negating the result as an alternative... but that's not quite correct :-)
Stephen C
To reverse the order use `Collections.reverseOrder(comparator)` (see http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#reverseOrder(java.util.Comparator))
Aaron Digulla
thanks guysproblem solved
chandra wibowo