I have seen most of the examples using Stream to sort a map by the value but most of them were using a slightly easy version than mine and did not work for my case.
There was this website for examples similar to my case but it did not work as well since it creates the "int cannot be dereferenced" error due to compareTo()
function as it is not for comparing primitives.
I also tried using Comparator.comparing()
but it had no effect on the sorting at all.
I have something like below;
Map<String, Person> sortedMap = sortPersonByValue(personMap);
public static Map<String, Person> sortPersonByValue(final Map<String, Person> regions) {
return regions.entrySet()
.stream()
.sorted(((e1, e2) -> e1.getValue().getAge().compareTo(e2.getValue().getAge()))
//.sorted(Comparator.comparing(e1 -> e1.getValue().getAge()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
I would appreciate it if someone could point out what I am doing wrong. Thanks