Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array list of hashmaps by the value(comparing by value of map) of the hashmaps [closed]

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.

like image 737
gayu312 Avatar asked Nov 23 '25 11:11

gayu312


1 Answers

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());
like image 69
shmosel Avatar answered Nov 26 '25 00:11

shmosel