gpt4 book ai didi

java - 如何在 Java Stream 上应用多个过滤器?

转载 作者:太空狗 更新时间:2023-10-29 22:51:56 26 4
gpt4 key购买 nike

我必须通过映射来过滤对象集合,该映射包含对象字段名称和字段值的键值对。我正在尝试通过 stream().filter() 应用所有过滤器。

对象实际上是 JSON,因此 Map 包含其变量的名称以及它们必须包含的值才能被接受,但是为了简单起见并且因为它与问题无关我写了一个简单的 Testclass用于模拟行为:

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;
}
}
}

到目前为止我尝试了什么:

public static void main(String[] args) {
List<TestObject> list = new ArrayList<>();
Map<Integer, Integer> filterMap = new HashMap<>();
list.add(new TestObject(1, 2, 3));
list.add(new TestObject(1, 2, 4));
list.add(new TestObject(1, 4, 3));
filterMap.put(3, 3); //Filter property3 == 3
filterMap.put(2, 2); //Filter property2 == 2

//Does not apply the result
filterMap.forEach((key, value) -> list.stream()
.filter(testObject -> testObject.getProperty(key) == value)
.collect(Collectors.toList())
);
/* Gives error: boolean can not be converted to void
list = list.stream()
.filter(testObject -> filterMap.forEach((key, value) -> testObject.getProperty(key) == value))
.collect(Collectors.toList()
);
*/
//Printing result

list.forEach(obj -> System.out.println(obj.getProperty(1) + " " + obj.getProperty(2) + " " + obj.getProperty(3)));
}

我尝试将 Map 的 forEach 放在第一位,然后将 Collection 的流放在第一位,但这两种解决方案都没有按预期工作。此示例的所需输出将仅打印具有值 property1=1、property2=2 和 property3=3 的对象。

我如何才能正确应用所有过滤器,就像在代码中一个接一个地使用固定数量的过滤器一样?

使用已知数量的过滤器:

list.stream().filter(...).filter(...)

编辑:

Sweeper 在他的回答中很好地总结了我的问题,所以在这里再次澄清(可能还有 future 的读者):我想保留所有满足所有过滤器的对象。

最佳答案

我想你想保留所有满足所有 map 指定条件的TestObjects

这将完成工作:

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

翻译成“英文”,

filter the list list by keeping all the elements x that:

  • all of the key value pairs y of filterMap must satisfy:
    • x.getProperty(y.getKey()) == y.getValue()

(我不认为我在使这个人类可读性方面做得很好......)如果你想要一个更具可读性的解决方案,我推荐 Jeroen Steenbeeke 的回答。

关于java - 如何在 Java Stream 上应用多个过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51187038/

26 4 0