简体   繁体   English

使用给定参数过滤Java流

[英]Filtering Java stream using a given parameter

I have a List<MyObject> : 我有一个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) . 第一个将按名称过滤MyObject,并将仅将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) . 第二个将使用我拥有的另一个函数( getState(MyObject.getTeam()) )由团队过滤MyObject,并将仅将其中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 由于您要检查同一对象的两个条件,因此可以在Predicate使用&&将它们聚合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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