Java 8 Stream filtering value of list in a list

守給你的承諾、 提交于 2020-01-11 04:43:21

问题


I have a an object which looks like the following

class MyObject {

    String type;
    List<String> subTypes;

}

Is it possible, given a list of MyObject's to use Java 8 streams to filter on both the type and then the subtype?

So far I have

myObjects.stream()
    .filter(t -> t.getType().equals(someotherType)
    .collect(Collections.toList());

but within this I also want another filter on each of the subTypes filtering those on a particular subtype too. I can't figure out how to do this.

An example would be

myObject { type: A, subTypes [ { X, Y, Z } ] }
myObject { type: B, subTypes [ { W, X, Y } ] }
myObject { type: B, subTypes [ { W, X, Z } ] }
myObject { type: C, subTypes [ { W, X, Z } ] }

I would pass in matchType B and subType Z, so I would expect one result -> myObject type B, subtypes: W, X, Z

the following currently returns 2 items in a list.

myObjects.stream()
    .filter(t -> t.getType().equals("B")
    .collect(Collectors.toList());

but I would like to add an additional filter over the each of the subtypes and only matching where 'Z' is present.


回答1:


You can do:

myObjects.stream()
         .filter(t -> t.getType().equals(someotherType) && 
                      t.getSubTypes().stream().anyMatch(<predicate>))
         .collect(Collectors.toList());

This will fetch all the MyObject objects which

  • meet a criteria regarding the type member.
  • contain objects in the nested List<String> that meet some other criteria, represented with <predicate>



回答2:


I saw the accepted answer from @kocko which is both a good answer and totally correct. However there is a slightly alternative approach where you simply chain the filters.

final List<MyObject> withBZ = myObjects.stream()
        .filter(myObj -> myObj.getType().equals("B"))
        .filter(myObj -> myObj.getSubTypes().stream().anyMatch("Z"::equals))
        .collect(Collectors.toList());

This is basically doing the same thing but the && operand is removed in favour of another filter. Chaining works really well for the Java 8 Stream API:s and IMO it is easier to read and follow the code.



来源:https://stackoverflow.com/questions/27822703/java-8-stream-filtering-value-of-list-in-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!