chandra wibowo
chandra wibowo

Reputation: 799

Sort collection of objects in HashMap based on the object's 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 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.

Upvotes: 2

Views: 2607

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328724

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)

Upvotes: 2

Stephen C
Stephen C

Reputation: 719229

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

Upvotes: 4

Related Questions