Java 8 stream filters the values in the list
•
Java
I have an object that looks like this
class MyObject { String type; List<String> subTypes; }
Is it possible to use Java 8 streams to filter types and subtypes given a MyObject list?
So far I have
myObjects.stream() .filter(t -> t.getType().equals(someotherType) .collect(Collections.toList());
But in this scope, I also want to use another filter on each subtype to filter the subtypes of a particular subtype I can't figure out how to do this
One example is
myObject { type: A,subTypes [ { X,Y,Z } ] } myObject { type: B,subTypes [ { W,X,Y } ] } myObject { type: B,Z } ] } myObject { type: C,Z } ] }
I will pass in matchtype B and subtype Z, so I want to get a result – > MyObject type B, subtype: W, Z
The following content currently returns 2 items in the list
myObjects.stream() .filter(t -> t.getType().equals("B") .collect(Collections.toList());
But I want to add an extra filter on each subtype and only match where "Z" exists
Solution
You can do:
myObjects.stream() .filter(t -> t.getType().equals(someotherType) && t.getSubTypes().stream().anyMatch(<predicate>)) .collect(Collectors.toList());
This will get all MyObject objects
>Meets the criteria for type members. > The objects contained in the nested list < string > meet some other criteria, represented by < predicate >
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码