Reputation: 49
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.
Upvotes: 0
Views: 2043
Reputation: 904
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
Upvotes: 1