Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting list of results not contained in same list with Java Streams

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.

like image 845
Derek Jones Avatar asked Sep 17 '25 08:09

Derek Jones


1 Answers

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());
like image 151
ernest_k Avatar answered Sep 19 '25 21:09

ernest_k