Java Stream使用多个过滤器(filter)或复杂条件方法用法及简单写法代码

本文主要介绍Java中,对List列表集合stream等,使用多个过滤器(filter)进行数据筛选,或使用复杂条件过滤数据的方法,以及简单写法代码。

示例类代码:

public class TestObject {
private int property1;
private int property2;
private int property3;
public TestObject(int property1, int property2, int property3) {
this.property1 = property1;
this.property2 = property2;
this.property3 = property3;
}
public int getProperty(int key) {
switch(key) {
case 1: return property1;
case 2: return property2;
default: return property3;
}
}
}

1、使用filter和allMatch实现

List<TestObject> newList = list.stream()
.filter(x ->
filterMap.entrySet().stream()
.allMatch(y ->
x.getProperty(y.getKey()) == y.getValue()
)
)
.collect(Collectors.toList());

2、使用for实现多个过滤条件

Stream<TestObject> stream = list.stream();
for (Predicate<TestObject> predicate: allPredicates) {
stream = stream.filter(predicate);
}
list = stream.collect(Collectors.toList());

3、使用foreach和filter实现

filterMap.forEach((key, value) -> list.stream()
.filter(testObject -> testObject.getProperty(key) == value)
.collect(Collectors.toList())
);

推荐阅读
cjavapy编程之路首页