繁体   English   中英

从 object 中为 Collectors.groupingBy(x, toSet()) 提取值

[英]Extracting a value from an object for Collectors.groupingBy(x, toSet())

所以,我试图在 object 的 id 值和 object 中的一组另一个值之间创建一个 map。 这个想法是每个 id 的对象都有多个关联类型,我需要创建一种方法来轻松引用给定数据集中与 ID 关联的类型。

例如;

public class exampleObj {
    public string id;
    public string type

    // getters and setters are supplied by lombok
}

Map<String, Set<String>> output = listOfExampleObj.stream().........

我正在寻找的结果是一个Map<String, Set<String>> ,键是 id,值是变量类型的集合,当 stream 迭代每个 exampleObj 时添加到集合中

我尝试了以下方法,但没有成功;

Map<String, Set<String>> typeMap = listOfExampleObjs.stream().collect(Collectors.groupingBy(p -> p.getId(), toSet(p.getType)));

Map<String, Set<String>> typeMap = listOfExampleObjs.stream().collect(Collectors.groupingBy(exampleObj::id, toSet(example::type)));

Map<String, Set<String>> typeMap = listOfExampleObjs.stream().collect(Collectors.groupingBy(exampleObj::id, groupingBy(exampleObj::type)));

是否有我缺少的 java 收集器? 我是否必须制作自定义收集器才能做到这一点?

下面是答案代码:


ExampleObj a = new ExampleObj("1", "a");
ExampleObj b = new ExampleObj("1", "b");
ExampleObj c = new ExampleObj("2", "a");
ExampleObj d = new ExampleObj("2", "b");
ExampleObj e = new ExampleObj("3", "c");
List<ExampleObj> exps = Arrays.asList(a,b,c,d,e);
Map<String, Set<String>> typeMap = exps.stream().collect(Collectors
                            .groupingBy(ExampleObj::getId, 
                                  Collectors.mapping(ExampleObj::getType,  
                                               Collectors.toSet())));  //groupby + mapping

System.out.println(typeMap); // {1=[a, b], 2=[a, b], 3=[c]}


暂无
暂无

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

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