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

前端 未结 1 1304
孤独总比滥情好
孤独总比滥情好 2021-01-14 17:54

This is a follow-up of How to get the count of keys for values in a hash map using lambda. I have a HashMap and I want to find the number of keys for each value

相关标签:
1条回答
  • 2021-01-14 18:27

    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;
    
    0 讨论(0)
提交回复
热议问题