How to apply multiple Filters on Java Stream?

后端 未结 4 763
梦毁少年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:16

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

    This will do the job:

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

    Translated into "English",

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

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

提交回复
热议问题