简体   繁体   English

Java 8 Streams groupingBy 收集器

[英]Java 8 Streams groupingBy collector

How would I get this data structure using Java 8 API?我将如何使用 Java 8 API 获取此数据结构?

This is my object structure:这是我的对象结构:

class A {

    B b;

    public A(B b) {
        this.b = b;
    }
}

class B {

    List<A> as;

    private int i;

    public B(int i) {
        this.i = i;
    }
}

I'm trying to aggregate it to我正在尝试将其汇总为

 Map<A, List<B>> bs;

from来自

List<A> as = new ArrayList<>();
as.add(a1);
as.add(a2);
as.add(a3);

With groupingBy:使用 groupingBy:

Map<B, List<A>> bs = as.stream().collect(Collectors.groupingBy(A::getB));

Assuming class A has a getB() method.假设类A有一个getB()方法。

It's pretty simple actually (assuming hashCode/equals is present in B )实际上非常简单(假设hashCode/equals存在于B

as.stream()
  .collect(Collectors.groupingBy(A::getB))

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

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