Search code examples
javalistjava-streampojo

Java Stream custom list based on List


I have seen many examples of streaming a java custom list, e.g. List<People>, to filter for a single value, e.g.

p -> p.Name.contains("john"). (People pojo has a few properties: Name, Age, Sex).

I want to actually stream without filtering on a single value but filtering on a list of strings, i.e.Instead of just "John", I can provide a list of items to filter against.

e.g. Pseudo: p -> p.Name.contains(List<String>)

I am hoping this is simple to explain without need for code.

Any ideas?


Solution

  • You can use List::contains to filter using a list of Strings:

    List<People> people = Arrays.asList(
            new People("John", 25, "M"),
            new People("Jane", 25, "F"),
            new People("Pete", 25, "M"),
            new People("Albert", 25, "M"),
            new People("Victor", 25, "M")
    );
    
    List<String> names = Arrays.asList("John", "Pete", "Victor");
    
    List<People> filtered = people.stream()
            .filter(p -> names.contains(p.getName())) // if the name of p is contained in the list of string names to filter
            .collect(Collectors.toList());
    

    Output:

    People{name='John', age=25, sex='M'}, 
    People{name='Pete', age=25, sex='M'}, 
    People{name='Victor', age=25, sex='M'}