bpg
11/7/2017 - 2:38 AM

Java8 Map sort by value reversed

Java8 Map sort by value reversed

// sort in order of values reversed
map.entrySet().stream()
    .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
  
// sort by some attribute of enty
// and collect back to another map preserving the new order
this.tasks.entrySet().stream()
    .sorted(Comparator.comparingInt(o -> o.getValue().getPriority()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

// group some values by some criteria, counting numbers in each group
Map<Integer, Long>  map = this.tasks.values().stream()
    .map(Task::getPriority)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));