I need to sort the hashmap based on value List size and its' not working. I've written my custom comparator. For example hashmap is as follow:
Test1-a,b
Test2-c,d,e
Test3-f
Test4-d,g,h,i
Test5-p,b
After sorting it should look like this:
Test3-f
Test1-a,b
Test5-p,b
Test2-c,d,e
Test4-d,g,h,i
Sorting the keys based on value list size in ascending order. I wrote this code and it's not working:
List<Map.Entry<String,List<String>>> list =
new ArrayList<>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<String,List<String>>>() {
public int compare( Map.Entry<String,List<String>> o1,
Map.Entry<String,List<String>> o2) {
return o1.getValue().size().compareTo(o2.getValue().size() );
}
});
CodePudding user response:
Your code is not compilabe, because List.size()
returns an (unboxed) int
.. we cannot invoke "methods" on that.
Instead try:
Collections.sort(
list,
// when java >= 8, we can save all the "decoration" (anonymous class), and "lambda" instead:
(o1,o2) -> Integer.compare(o1.getValue().size(), o2.getValue().size())
);
Javadoc (Integer.compare(int x, int y)
): https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/Integer.html#compare(int,int)
Its implementation looks as simple as:
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
CodePudding user response:
Putting the above answer together with your code, you could do
List<Map.Entry<String,List<String>>> list =
m.entrySet()
.stream()
.sorted((e1, e2) -> Integer.compare(e1.getValue().size(), e2.getValue().size()))
.collect(Collectors.toList());
System.out.println(list);