简体   繁体   中英

Filtering Java stream using a given parameter

I have a List<MyObject> :

My Object:
    String name;
    String team;

EDIT: I want to create a function that will filter this list using two parameters:

public List<MyObject> filterMyObjectList (String name, String state, List<MyObject> objectsList)

I need to create two filters:

The first will filter the MyObject by the name, and will add to the returned list only objects where the MyObject.getName().equals(name) .

The second will filter the MyObject by the team using another function that I have ( getState(MyObject.getTeam()) ), and will add to the list only objects where the getState(MyObject.getTeam()).equals(state) .

Is there a way to write a predicate like this? Using a variable to compare? Is there another way to filter using comparison?

Thanks!

To do this you can just apply a filter:

public List<MyObject> filterMyObjectList (String name, String state, List<MyObject> objectsList) {
   return objectsList.stream()
                     .filter(obj -> obj.getName().equals(name) && getState(obj.getTeam()).equals(state))
                     .collect(Collectors.toList());
}

Since you are checking two conditions of the same object, you can aggregate them with && in the Predicate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM