代码之家  ›  专栏  ›  技术社区  ›  Bohao LI

如何按成对流的键分组

  •  -1
  • Bohao LI  · 技术社区  · 6 年前

    假设我有以下流:

    ...
    import javafx.util.Pair;
    ...
    Pair[] testPairs = {
            new Pair<>("apple", "James"),
            new Pair<>("banana", "John"),
            new Pair<>("grapes", "Tom"),
            new Pair<>("apple", "Jenkins"),
            new Pair<>("banana", "Edward"),
            new Pair<>("grapes", "Pierre")
    };
    
    Map<String, List<String>> result1 = Arrays.stream(testPairs)...;
    
    Map<String, String> result2 = Arrays.stream(testPairs)...;
    

    结果1 ,我想按对的键进行分组,得到所有对应的名称。 为了 结果2 ,我想按键分组,然后从 (指先前的结果)。

    如何通过使用Java8流api来实现这一点?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Youcef LAIDANI    6 年前

    Map<String, List<String>> result1 = Arrays.stream(testPairs)
        .collect(Collectors.groupingBy(Pair::getS, 
            Collectors.mapping(Pair::getT, Collectors.toList())));
    
    Map<String, String> result2 = Arrays.stream(testPairs)
        .collect(Collectors.toMap(Pair::getS, Pair::getT, (v1, v2) -> v1));
    

    如果您将行类型与数组一起使用,那么下面是一个版本,其中包含由YCF\ L在下面的注释中指定的必要强制转换。

    Map<String, List<String>> result1 = Arrays.stream(testPairs)
            .collect(Collectors.groupingBy(p -> (String) p.getKey(),
                    Collectors.mapping(p -> (String) p.getValue(), Collectors.toList())));
    
    Map<String, String> result2 = Arrays.stream(testPairs)
                    .collect(Collectors.toMap(
                            p -> (String) p.getKey(), 
                            p -> (String) p.getValue(), 
                            (a, b) -> b)
                    );
        }