如何通过Set size总和对Map <string,list <set <long =“” >>>进行排序?

时间:2019-05-18 12:34:34

标签: java java-8 java-stream

如何按Set大小和对Map(String,List(Set(Long)))进行排序? 我有一个像这样的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

我希望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

2 个答案:

答案 0 :(得分:4)

使用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));

答案 1 :(得分:1)

您将可以对其执行一些操作,但是实际上不可能对值进行HashMap排序。

但是,如果您知道要对其执行的操作,则可以使用以下解决方案。

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);

存在getSumOfSetCount()

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