How to apply multiple Filters on Java Stream?

后端 未结 4 726
梦毁少年i
梦毁少年i 2021-01-11 09:27

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().filt

4条回答
  •  执笔经年
    2021-01-11 10:04

    It has nothing to do with filter. Actually the filter never work as per your code. Look at

    //Does not apply the result
    filterMap.forEach((key, value) -> list.stream()
            .filter(testObject -> testObject.getProperty(key) == value)
            .collect(Collectors.toList())
    );
    

    List has been filtered but nothing is changed here. No element has been deleted and No object address has been changed either. Try removeIf

    // Does not apply the result
    filterMap.forEach((key, value) -> list.removeIf(testObject -> testObject.getProperty(key) != value));
    

    output is

    1 2 3
    

提交回复
热议问题