Neil
Neil

Reputation: 3036

How to use stream to filter a collection in a range

I have a domain as person

public class Person{
  String name;
}

I have a list String of person names, like

listRange = new ListWith("Bob","John","Mark");

And how can I use Java 8 stream to filter in resultList, which person has the name in this range list. It might be like

resultList.stream().filter(p->p.getName().equals(listRange.any).collect();

How can I use Lambda to filter the resultList?

Upvotes: 2

Views: 1069

Answers (1)

Tunaki
Tunaki

Reputation: 137064

What you are looking for is just the contains method:

resultList.stream().filter(p -> listRange.contains(p.getName()))
                   .collect(Collectors.toList());

If your name list is only used to filter out persons from your result, you should consider using a Set as its contains method is O(1) (constant-time) so it will result in better performance.

Upvotes: 8

Related Questions