根据对象的变量对 HashMap 中的对象集合进行排序
我在 HashMap 中有一个书籍对象的集合。这本书有 book_title、book_author、book_year_published 等。我想根据 book_title (一个 String)对它们进行升序和降序排序,并将它们显示在屏幕上。
我希望有人可以帮助我 - 我已经这样做了几个小时,但仍然没有找到解决方案。提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于您只想对书籍进行排序,因此从概念上讲不需要使用 Map 作为目标数据结构。
SortedSet
甚至List
似乎是更合适的类型。这是一个骨架解决方案:要按不同的顺序排序(例如按书名降序),定义替代比较器类并填充不同的树集。
(如果你要对一个非常大的书籍哈希图进行排序,使用 ArrayList 和快速排序可能比使用 TreeSet 和树插入排序更有效。但是对于任何足够小的书籍集合,你会考虑在屏幕上显示它,排序效率不是一个问题。)
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 aList
seems a more appropriate type. Here is a skeleton solution: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.)
将
TreeMap
与自定义Comparator
:为您提供
HashMap
的排序版本。要反转顺序,请使用
(请参阅 文档)
Use a
TreeMap
with a customComparator
:gives you a sorted version of your
HashMap
.To reverse the order, use
(see the docs)