How to sort hash map based on number of keys for a value using flatmap java8?

依然范特西╮ 提交于 2019-12-01 09:25:18

You could have the following:

Map<Integer, List<Integer>> sorted = 
    map.entrySet()
       .stream()
       .sorted(comparing(e -> ex.get(e.getKey()), reverseOrder()))
       .collect(toMap(
           Map.Entry::getKey,
           e -> e.getValue().stream().sorted(comparing(ex::get, reverseOrder())).collect(toList()),
           (v1, v2) -> { throw new IllegalStateException(); },
           LinkedHashMap::new
       ));

This creates a Stream of the entries of the map, sorts them in reverse order according the count of keys for that entry's key and finally collects that into a map where the new value is sorted in reverse order with regard to the count of each integer (ex::get). The collecting map is a LinkedHashMap to preserve encounter order.

Output:

{1=[2, 3, 0], 2=[4, 1, 0], 3=[4, 1, 5], 4=[2, 3, 5], 0=[1, 2], 5=[4, 3]}

Static imports used:

import static java.util.Comparator.comparing;
import static java.util.Comparator.reverseOrder;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!