【问题标题】:List from List Streams JAVA8List Streams JAVA8 中的列表
【发布时间】:2019-06-21 20:01:20
【问题描述】:

我需要通过列表(B 类)中的一个列表(A 类)。我想使用流 JAVA8,但是通过第二个列表我失去了第一个列表的引用

class A {
   Collection<B> listB ;
   String x;
   // Some other variables
}

class B {
   String y;
   // Some other variables
}

// List object A

Collection<class A> listA;

listA.stream()
    .filter(a -> a.getListaB() != null)
    .flatMap(a -> a.getListB().stream())
    .forEach(b -> {
                // Here lose reference object A
                // I need something like a.getX()
                // I need too use something like b.getY(), use both lists
                    });

错误是“找不到simbol变量a”我理解错误,有没有使用流而不是foreach或for循环的解决方案?

【问题讨论】:

    标签: list java-8 java-stream


    【解决方案1】:

    因为您没有将第二个流嵌套到第一个流,而是将其展平:

    .flatMap(a -> a.getListB().stream())
    

    因此,最后在此语句之后,您将得到 Lists 的 B 的所有元素的 stream&lt;B&gt;

    为了解决您的要求,嵌套流并使用forEach() 而不是flatMap(),因为在这里您不想转换任何东西,但您想应用Consumer

    Collection<A> listA = ...;
    
    listA.stream()
        .filter(a -> a.getListaB() != null)
        .forEach(a -> a.getListB().stream()
                   .forEach(b -> {
                        // a and b are usable now
                    })
           );
    

    【讨论】:

    • 非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2018-05-31
    • 2017-08-28
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多