-4

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?

PKB
  • 51
  • 7

2 Answers2

2

You can't. HashMap cannot be sorted, since they are hashed instead.

Either use a TreeMap to keep your keys in order, or put your data in a List so that you can put them in whatever order you want, included sorted order by calling sort().

kumesana
  • 2,495
  • 1
  • 9
  • 10
1

Flatten the sets to a single list like so :

List<MyObject> allObj = myMap.values().forEach(list::addAll);

Then sort the list :

allObj.sort(Comparator.comparing(a -> a.name));
raviiii1
  • 936
  • 8
  • 24