Filter stream using correlation between stream elements

Viewed 317

Let’s say there’s a Person class that looks like this:

public class Person {
    private int id;
    private String discriminator;
    // some other fields plus getters/setters
}

Now I have a Stream of Person elements and that stream may contain multiple Person instances that have same id, but different discriminator values, i.e. [Person{“id”: 1, “discriminator”: “A”}, Person{“id”: 1, “discriminator”: “B”}, Person{“id”: 2, “discriminator”: “A”}, ...]

What I’d like to do is to filter out all Person instances with some id if there’s at least one Person instance with that id that has a particular discriminator value. So, continuing with the above example, filtering by discriminator value “A” would yield an empty collection (after the reduction operation, of course) and filtering by discriminator value “B” would yield a collection not containing any Person instance with id equal to 1.

I know I can reduce the stream using groupingBy collector and group elements by Person.id and then remove the mapping from the resulting Map if the mapped list contains a Person element with the specified discriminator value, but am still wondering if there’s a simpler way to achieve the same result?

3 Answers

If I understood your problem correctly, you would first find all IDs that would match a discriminator:

Set<Integer> ids = persons.stream()
       .filter(p -> "A".equalsIgnoreCase(p.getDiscriminator()))
       .map(Person::getId)
       .collect(Collectors.toSet())

And then remove the entries that would match those:

persons.removeIf(x -> ids.contains(x.getId()))

Eugenes answer works great, but I personally prefer a single statement. So I took his code and put it all together into a single operation. Which looks like this:

final List<Person> result = persons.stream()
    .filter(p -> "B".equalsIgnoreCase(p.getDiscriminator()))
    .map(Person::getId)
    .collect(
        () -> new ArrayList<>(persons),
        ( list, id ) -> list.removeIf(p -> p.getId() == id),
        ( a, b ) -> {throw new UnsupportedOperationException();}
    );

Probably need to mention that the copy of persons is needed, else the Stream will corrupt and encounters null values.

SideNote: This version is currently throwing an UnsupportedOperationException when trying to use in parallel.

So below I present the solution that I've come up with. First I group the input Person collection/stream by the Person.id attribute and then I stream over the map entries and filter out those that have at least one value that matches given discriminator.

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
            new Person(1, "A"),
            new Person(1, "B"),
            new Person(1, "C"),
            new Person(2, "B"),
            new Person(2, "C"),
            new Person(3, "A"),
            new Person(3, "C"),
            new Person(4, "B")
        );

        System.out.println(persons);
        System.out.println(filterByDiscriminator(persons, "A"));
        System.out.println(filterByDiscriminator(persons, "B"));
        System.out.println(filterByDiscriminator(persons, "C"));
    }

    private static List<Person> filterByDiscriminator(List<Person> input, String discriminator) {
        return input.stream()
            .collect(Collectors.groupingBy(Person::getId))
            .entrySet().stream()
            .filter(entry -> entry.getValue().stream().noneMatch(person -> person.getDiscriminator().equals(discriminator)))
            .flatMap(entry -> entry.getValue().stream())
            .collect(Collectors.toList());
    }

}

class Person {

    private final Integer id;
    private final String discriminator;

    public Person(Integer id, String discriminator) {
        Objects.requireNonNull(id);
        Objects.requireNonNull(discriminator);
        this.id = id;
        this.discriminator = discriminator;
    }

    public Integer getId() {
        return id;
    }

    public String getDiscriminator() {
        return discriminator;
    }

    @Override
    public String toString() {
        return String.format("%s{\"id\": %d, \"discriminator\": \"%s\"}", getClass().getSimpleName(), id, discriminator);
    }
}
Related