0

I have one simple array with custom object and want to filter with java 8 stream.

    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.

2
  • Your array size should be 2. So the declaration should be changed like: A[] aArray = new A[2]; Commented Mar 10, 2019 at 5:04
  • As an aside define yourself some good constructors so you may do just A[] aArray = new A[] { new A(1, "AName1", new B(1, "BName1")), new A(2, "AName2", new B(2, "BName2")), null };. Commented Mar 10, 2019 at 8:18

1 Answer 1

1

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

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

And Iterate List

Sign up to request clarification or add additional context in comments.

3 Comments

Calling Optional.get is always a mistake.
@BoristheSpider Corrected, Thanks :)
.orElse(null) always gives me depression... With Optional why do you even want to use null? You can just return Optional and that all - no sense to mapping it to null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.