public int rarest(Map<String, Integer> m) throws Exception
Count the number of occurrences for each age
You can apply a groupingBy()
on m
's values, using Collectors.counting()
to populate the intermediate map's values:
// assume map is the method argument
Map<Integer, Long> temp = map.entrySet().stream()
.collect(Collectors.groupingBy(Entry::getValue, Collectors.counting()))
Sort by the least values, then by the youngest age
From this intermediate map, you can stream the entries, sort by the values using a custom Comparator
lambda declaration and then return the first entry, i.e. the rarest:
temp.entrySet().stream()
.sorted((e1, e2) -> {
int v = e1.getValue().compareTo(e2.getValue());
return v != 0 ? v : e1.getKey().compareTo(e2.getKey());
})
.findFirst().map(Entry::getKey).get().intValue();
public static int rarest(Map<String, Integer> map) {
return map.entrySet().stream()
.collect(Collectors.groupingBy(Entry::getValue,
Collectors.counting()))
.entrySet().stream()
.sorted((e1, e2) -> {
int v = e1.getValue().compareTo(e2.getValue());
return v != 0 ? v : e1.getKey().compareTo(e2.getKey());
})
.findFirst().map(Entry::getKey).get().intValue();
}