My list looks something like this
List<Map<CustomClass,Integer>> sampleList = new ArrayList<>();
Here each custom class is associated with a value where the class is taken as key and the value associated to it is the value for the map. I can have more than one 1 key to have same value.
For example:
List<Map<CustomClass,Integer>> sampleList = new ArrayList<>();
CustomClass a1 = new CustomClass();
CustomClass a2 = new CustomClass();
CustomClass b1 = new CustomClass();
CustomClass b2 = new CustomClass();
Map<CustomClass, Integer> map1 = new HashMap();
map1.put(a1,3);
map1.put(a2,3);
Map<CustomClass, Integer> map2 = new HashMap();
map2.put(b1,2);
map2.put(b2,2);
sampleList.add(map1);
sampleList.add(map2);
Now I want the final sorted list to be having {b1,b2,a1,a2} i.e sorted based on integer value.
You can use streams to flatten the maps and sort by value:
List<CustomClass> result = sampleList.stream()
.map(Map::entrySet)
.flatMap(Set::stream)
.sorted(Entry.comparingByValue())
.map(Entry::getKey)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With