开发者

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_publishe开发者_开发问答d, 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.


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


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜