如何在Java Stream上应用多个过滤器? [英] How to apply multiple Filters on Java Stream?

查看:378
本文介绍了如何在Java Stream上应用多个过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过Map过滤对象集合,它包含对象字段名称和字段值的键值对。我试图通过stream()。filter()来应用所有过滤器。

I have to filter a Collection of Objects by a Map, which holds key value pairs of the Objects field names and field values. I am trying to apply all filters by stream().filter().

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

The Objects are actually JSON, therefore the Map holds the names of its variables as well as the value they have to contain in order to be accepted, but for simplicity reasons and because its not relevant to the question I wrote a simple Testclass for simulating the behaviour:

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

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

What I have tried so far:

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

我首先尝试将每个地图放入地图,然后先收集集合流,但这两种解决方案都没有按预期工作。此示例的所需输出仅用于打印值为property1 = 1,property2 = 2和property3 = 3的对象。

I tried putting forEach of the Map first and the stream of the Collection first, but both solutions did not work as intended. The desired output of this example would be only to print the object with the values property1=1, property2=2 and property3=3.

如何正确应用所有过滤器比如什么时候你会在代码中一个接一个地使用固定数量的过滤器?

How can I apply all filters correctly like when you would put them one after another in the code with a fixed amount of filters?

使用已知数量的过滤器:

With a known amount of filters:

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

编辑:

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

Sweeper summed my question up very well in his answer, so just for clarification (and probably future readers) here again: I want to keep all Objects that satisfy all filters.

推荐答案

我想你要保留所有 TestObjects 满足所有地图指定的条件?

I suppose you want to keep all the TestObjects that satisfy all the conditions specified by the map?

这将完成工作:

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

翻译成English,

Translated into "English",


过滤列表列表保留所有元素 x 表示:

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


  • 所有键值对 y filterMap 必须满足:


    • x.getProperty(y.getKey( ))== y.getValue()

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

      (我认为我没有做好这个人类可读的工作......)如果你想要一个更易读的解决方案,我推荐Jeroen Steenbeeke的答案。

      (I don't think I did a good job at making this human readable...) If you want a more readable solution, I recommend Jeroen Steenbeeke's answer.

      这篇关于如何在Java Stream上应用多个过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆