I have a LinkedHashMap< Integer, HashSet< Integer > > and I want to sort the keys based on decreasing order of the size of their values. I currently have this fragment from another thread but I'm not sure how to change it to work with my case.
myMap.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(x,y) -> {throw new AssertionError();},
LinkedHashMap::new
));
Here's what I've tried
List<Map.Entry<String, Integer>> entries =
new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a, Map.Entry<String,Integer> b){
return a.getValue().size().compareTo(b.getValue().size());
}
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
I just added the .size() in there. I found it from this thread. The size I'm referring to is the number of items in the HashSet. It is usually just getValue().size() but it's not working here.