首页 > 解决方案 > Sort a hash map which contains set of an objects

问题描述

I have a hashmap of a structure: Map<Integer,Set<class-object>> mymap = new HashMap<>() In the map key is the integer and values are set of class objects The class-object has the following variables in it

{
  Integer id 
  String name
}

I want to sort the map in alphabetical order based on the class-object.name variable. How can we sort this map? Is it possible to sort such type of hashmap?

标签: javacollectionsjava-8

解决方案


你不能。HashMap 无法排序,因为它们是散列的。

要么使用 TreeMap 来保持键的顺序,要么将数据放在 List 中,这样你就可以按照你想要的任何顺序放置它们,包括通过调用 sort() 来排序。


推荐阅读