Warm tip: This article is reproduced from stackoverflow.com, please click
filter java java-stream collections set

Java Stream Filter based on a Set-type

发布于 2020-03-31 23:01:06

Is there any way to filter a Set field in a Stream or List based on a Set using Lambda Stream?

Example:

    List<Person> persons = new ArrayList<Person>();
    Set<String> hobbySet1 = new HashSet<String>();
    hobbySet1.add("H1");
    hobbySet1.add("H2");
    hobbySet1.add("H3");

    Set<String> hobbySet2 = new HashSet<String>();
    hobbySet2.add("H2");
    hobbySet2.add("H4");

    Set<String> hobbySet3 = new HashSet<String>();
    hobbySet3.add("H3");

    Set<String> hobbySet4 = new HashSet<String>();
    hobbySet4.add("H4");

    persons.add(new Person("P1", hobbySet1));
    persons.add(new Person("P2", hobbySet2));
    persons.add(new Person("P3", hobbySet3));
    persons.add(new Person("P4", hobbySet4));

    Set<String> searchHobby = new HashSet<String>();
    searchHobby.add("H1");
    searchHobby.add("H3");

I want to filter hobbies from List persons based on searchHobby, so that only those persons who have their hobbies specified in searchHobby will be retained.

I know how to achieve this using a simple for loop.

    List<Person> result = new ArrayList<Person>();

    for (String sHobby : searchHobby) {
        for (Person p : persons) {
            Set<String> pHobbySet = p.getHobbies();
            for (String pHobby : pHobbySet) {
                if (pHobby.equalsIgnoreCase(sHobby)) {
                    Optional<Person> wasAdded = result.stream().filter(s->s.getName()==p.getName()).findAny();
                    if(wasAdded.isEmpty()) {
                        result.add(p);
                        break;
                    }
                }
            }
        }
    }

I'm looking for a java Stream Filter solution.


P.S. Person

public class Person {
    String name;
    Set<String> hobbies;

    public Person(String name, Set<String> hobbies) {
        this.name = name;
        this.hobbies = hobbies;
    }

    public String getName(){
        return name;
    }

    public Set<String> getHobbies(){
        return hobbies;
    }
}
Questioner
alex
Viewed
64
Red_Shuhart 2020-01-31 20:33

anyMatch will return true if some hobby matches.

List<Person> personsWithHobby = persons.stream()
    .filter(person -> person.getHobbies().stream()
            .anyMatch(searchHobby::contains))
    .collect(Collectors.toList());