Java 8 value filtering list flow in a list

I have an object that looks like this

class MyObject { String type; List<String> subTypes; } 

Is it possible, given the MyObject list, to use Java 8 threads to filter both type and subtype?

I still have

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

but inside this I also want each subtype to have another filter that also filters them by a specific subtype. 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 go into matchType B and subType Z, so I would expect a single result -> myObject of type B, subtypes: W, X, Z

the following currently returns 2 items in the list.

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

but I would like to add an additional filter for each of the subtypes and only combine where "Z" is present.

+7
java java-8
source share
2 answers

You can do:

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

This will get all MyObject that are

  • match the criteria for a type member.
  • contain objects in a nested List<String> that satisfy some other criteria provided by <predicate>
+10
source share

I saw the accepted answer from @kocko, which is a good answer and absolutely correct. However, there is a slightly alternative approach when you simply link 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 basically does the same, but the && operand is removed in favor of another filter. The chain works very well for the Java 8 Stream API: s and IMO are easier to read and follow code.

+8
source share

All Articles