如何按值大小对Map条目进行排序,其中map值是一个集合?

3
有没有一种方法可以按值进行地图条目排序,其中值是集合?我希望按其集合大小对条目进行排序。 我迄今为止的代码:
public Map<Object, Collection<Object>> sortByCollectionSize() {
    return myMap.entrySet().stream().sorted(Map.Entry.<Object, Collection<Object>>comparingByValue())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
1个回答

3
您可以使用Comparator.comparingInt将其运作如下:
return myMap.entrySet()
            .stream()
            .sorted(Comparator.comparingInt(e -> e.getValue().size()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接