简体   繁体   English

如何通过Set size sum对Map <String,List <Set <Long >>>进行排序?

[英]How to sort a Map<String, List<Set<Long>>> by the Set size sum?

How can I sort a Map(String, List(Set(Long))) by the Set size sum? 如何通过Set size sum对Map(String,List(Set(Long))进行排序? I have a HashMap like this: 我有一个像这样的HashMap:

myMap.put("monday", [[3215, 5654], [5345], [3246, 7686, 4565]]) // 6 Long elements in total
myMap.put("tuesday", [[3215, 5654], [5345, 2879, 6734], [3246, 7686, 4565]]) // 8 Long elements in total
myMap.put("wednesday", [[9845, 2521], [0954]]) // 3 Long elements in total

I expect the myMap sorted like this: 我希望myMap像这样排序:

("tuesday", [[3215, 5654], [5345, 2879, 6734], [3246, 7686, 4565]]) // 8 Long elements in total
("monday", [[3215, 5654], [5345], [3246, 7686, 4565]]) // 6 Long elements in total
("wednesday", [[9845, 2521], [0954]]) // 3 Long elements in total

Use LinkedHashMap for sorting: 使用LinkedHashMap进行排序:

Map<String, List<Set<Long>>> result = map.entrySet()
    .stream()
    .sorted(Comparator.comparingInt(e->e.getValue().stream().mapToInt(Set::size).sum()))
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

You would be able to perform some operations on it, but keeping a HashMap sorted on value is indeed not possible. 您将能够对其执行某些操作,但确实不能对HashMap进行按值排序。

However, if you know the operations you want to perform on it, you may use the following solution. 但是,如果您知道要对其执行的操作,则可以使用以下解决方案。

myMap.entrySet()
     .stream()
     .sorted((entry1, entry2) -> {
         Integer sum1 = getSumOfSetCount(entry1.getValue());
         Integer sum2 = getSumOfSetCount(entry2.getValue());
         return Integer.compare(sum1, sum2);
     })
     .forEach(entry -> // perform operation);

With getSumOfSetCount() being 使用getSumOfSetCount()

public int getSumOfSetCount(List<Set<Long>> list) {
    return (int) list.stream()
                     .flatMap(Stream::of)
                     .count();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM