Lets say I have a list of ToFilter
objects that look as follows:
private class ToFilter {
String option1;
String option2;
}
Using Java streams I want to filter out all elements where option 1 is not contained in any other object's option 2. So for example if there are 4 instances of ToFilter with:
option1 = C,
option2 = A
option1 = C,
option2 = F
option1 = A,
option2 = B
option1 = A,
option2 = D
C should be filtered and contained in the result set because it has entries in option1
but not option2
of any other object. Something like the nonematch()
, but that actually returns a list of ToFilter
objects rather than just a boolean true.
I would use two streams, creating a set of all option2
values against which I check option1
values from the collection:
List<ToFilter> list = ...;
Set<String> option2Set = list.stream()
.map(ToFilter::getOption2)
.collect(Collectors.toSet());
List<ToFilter> filtered = list.stream()
.filter(f -> !option2Set.contains(f.getOption1()))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With