Reputation: 1222
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.
Upvotes: 1
Views: 794
Reputation: 7956
What you've tried was close. Here's a fixed version:
List<Map.Entry<Integer, Set<Integer>>> entries = new ArrayList<>(
map.entrySet());
Collections.sort(entries,
new Comparator<Map.Entry<Integer, Set<Integer>>>() {
public int compare(Map.Entry<Integer, Set<Integer>> a,
Map.Entry<Integer, Set<Integer>> b) {
return Integer.compare(
a.getValue().size(),
b.getValue().size());
}
});
Map<Integer, Set<Integer>> sortedMap = new LinkedHashMap<>();
for (Map.Entry<Integer, Set<Integer>> entry : entries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
Setting up with
LinkedHashMap<Integer, Set<Integer>> map = new LinkedHashMap<>();
map.put(1, new HashSet<>(Arrays.asList(1,2,3)));
map.put(2, new HashSet<>(Arrays.asList(1,2)));
map.put(3, new HashSet<>(Arrays.asList(1)));
and running
System.out.println(sortedMap);
after sorting outputs
{3=[1], 2=[1, 2], 1=[1, 2, 3]}
Upvotes: 1