Java 如何对地图进行排序<;字符串,列表<;设置<;长期>&燃气轮机&燃气轮机;按设定的大小和?

Java 如何对地图进行排序<;字符串,列表<;设置<;长期>&燃气轮机&燃气轮机;按设定的大小和?,java,java-8,java-stream,Java,Java 8,Java Stream,如何按设置的大小和对映射(字符串、列表(集合(长))进行排序? 我有这样一个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.

如何按设置的大小和对映射(字符串、列表(集合(长))进行排序? 我有这样一个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
("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
我希望myMap的排序如下:

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
("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

您可以对它执行一些操作,但是根据值对
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();
}
public int getSumOfSetCount(列表){
return(int)list.stream()
.flatMap(流::of)
.count();
}

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

地图只能按键排序。如果你想排序,不要使用地图。使用列表。取决于你想用什么当然。。。