简体   繁体   English

Java 8数组流过滤器

[英]Java 8 Array Stream Filter

I have one simple array with custom object and want to filter with java 8 stream. 我有一个带有自定义对象的简单数组,并希望使用java 8流进行过滤。

    A[] aArray = new A[3];

    A a1 = new A();
    a1.setaId(1);
    a1.setaName("AName1");

    B b1 = new B();
    b1.setbId(1);
    b1.setbName("BName1");

    a1.setB(b1);
    aArray[0] = a1;

    A a2 = new A();
    a2.setaId(2);
    a2.setaName("AName2");

    B b2 = new B();
    b2.setbId(2);
    b2.setbName("BName2");

    a2.setB(b2);
    aArray[1] = a2;

Can you please suggest how can I go for filter stream on array NOT ON arrayList 你能建议我如何在数组上去过滤流吗?

Basically I want to filter with only "BName2" value. 基本上,我只想使用“ BName2”值进行过滤。

If you are storing unique element in the array then you can use following approach 如果要在数组中存储唯一元素,则可以使用以下方法

If the object is Unique 如果对象是唯一的

A aWithValidString = Arrays.stream(aArray)
    .filter(a -> "BName2".equals(a.getB().getbName()))
    .finAny().orElse(null);

If you have multiple Objects in Array with "Bname2" string you can use Below code 如果数组中有多个带有“ Bname2”字符串的对象,则可以使用以下代码

List<A> filteredObject = Arrays.stream(aArray)
    .filter(a -> "BName2".equals(a.getB().getbName()))
    .collect(Collectors.toList());

And Iterate List 和迭代列表

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

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