pri :
I'm not able to convert below snippet in Java 8 stream format.
List<String> titles = Arrays.asList("First Name", "Last Name");
for (FirstClass first : firstClassList) {
for (SecondClass second : first.getSecondClassList()) {
for (ThirdClass third : second.getThirdClassList()) {
if(!titles.contains(third.getField())) {
second.getThirdClassList().remove(third);
}
}
}
}
I'm comparing third level nested list object against the input list of fields. If fields are not matching then I'm removing them from original list. How can I achieve this using Java 8 syntax.
Edit: I want List of FirstClass to be returned.
Misha :
I don't think streams win you anything in this case. All you do is iterate over the nested lists and either the enhanced for loop or forEach
is more straightforward.
The improvements can come from using removeIf
to modify the list and, possibly, from moving the rejection logic out of the loop:
Predicate<ThirdClass> reject = third -> !titles.contains(third.getField());
firstClassList.forEeach(first ->
first.getSecondClassList().forEach(second ->
second.getThirdClassList().removeIf(reject)
)
);