如何通过嵌套地图值对外部地图进行排序

时间:2019-07-02 12:28:11

标签: java sorting java-stream

我对Java 8排序方法有疑问。

我有以下结构:

Map<String, Map<String, Long>>

我要实现的目标是先按外部地图的键(强制顺序)对外部地图进行排序,然后再按内部地图值的总和(Longs)排序,然后以正确的顺序将其放入Map.Entry列表中。我设法用第一个条件对它进行排序,但是无法使它与第二个条件(thenComparing方法)一起工作-出现类型错误。

queryResult.allCountersArray = queryResult.allCounters.entrySet().stream()
        .sorted(Map.Entry.<String, Map<String, Long>>comparingByKey(Comparator.comparing(term -> term.getSortingKey()))
                .thenComparing(Map.Entry.<String, Map<String, Long>>comparingByValue(Map.Entry.<String, Long>comparingByValue()))
        )
        .collect(Collectors.toList());


Error:(87, 49) java: no suitable method found for comparingByValue(java.util.Comparator<java.util.Map.Entry<java.lang.String,java.lang.Long>>)
    method java.util.Map.Entry.<K,V>comparingByValue() is not applicable
      (explicit type argument java.util.Map<java.lang.String,java.lang.Long> does not conform to declared bound(s) java.lang.Comparable<? super java.util.Map<java.lang.String,java.lang.Long>>)
    method java.util.Map.Entry.<K,V>comparingByValue(java.util.Comparator<? super V>) is not applicable
      (argument mismatch; java.util.Comparator<java.util.Map.Entry<java.lang.String,java.lang.Long>> cannot be converted to java.util.Comparator<? super java.util.Map<java.lang.String,java.lang.Long>>)

2 个答案:

答案 0 :(得分:1)

在这种情况下,您不能使用comparingByValue,因为您不想按内部地图的各个条目进行排序。

您能做的最好的事情是:

List<Entry<String, Map<String, Long>>> result = queryResult.entrySet()
        .stream()
        .sorted(Comparator.comparing(Entry<String, Map<String, Long>>::getKey)
                .thenComparingLong(e -> e.getValue()
                        .values()
                        .stream()
                        .mapToLong(i -> i)
                        .sum()))
        .collect(Collectors.toList());

List<Entry<String, Map<String, Long>>> result2 = queryResult.entrySet()
        .stream()
        .sorted(Entry.<String, Map<String, Long>>comparingByKey()
                .thenComparingLong(e -> e.getValue()
                        .values()
                        .stream()
                        .mapToLong(i -> i)
                        .sum()))
        .collect(Collectors.toList());

答案 1 :(得分:0)

这应该有效:

/Applications/MAMP\ PRO.app/Contents/MacOS/MAMP\ PRO cmd createHost "$DOMAIN" "$PATH"
/Applications/MAMP\ PRO.app/Contents/MacOS/MAMP\ PRO cmd stopServers
/Applications/MAMP\ PRO.app/Contents/MacOS/MAMP\ PRO cmd startServers