How can I sort a Map based upon on the size of its Collection values?

后端 未结 2 1323
你的背包
你的背包 2020-12-08 23:36

I have a HashMap like this:

Map> map = new HashMap<>();

map.put(\"USA\", Arrays.asList(\"CA\",\"IA\",\"I         


        
2条回答
  •  借酒劲吻你
    2020-12-08 23:40

    HashMap does not have a guaranteed iteration order so you will need to collect to a LinkedHashMap in order for the sorting to be meaningful.

    import static java.util.Comparator.comparingInt;
    import static java.util.stream.Collectors.toMap;
    
    Map> sorted = map.entrySet().stream()
        .sorted(comparingInt(e -> e.getValue().size()))
        .collect(toMap(
            Map.Entry::getKey,
            Map.Entry::getValue,
            (a, b) -> { throw new AssertionError(); },
            LinkedHashMap::new
        )); 
    

    The AssertionError is thrown because a combiner function is only used on parallel streams, which we are not using.

    You can also use comparingByValue if you find it more readable:

    import static java.util.Map.Entry.comparingByValue;
    
    Map> sorted = map.entrySet().stream()
        .sorted(comparingByValue(comparingInt(List::size)))
        // ... as above
    

提交回复
热议问题