Max Beaver
Max Beaver

Reputation: 93

Filter more times in a Java 8 Stream

Is it possible to filter more times in a Stream? For example if I have a list with IDs and I want to Stream a HashMap and map the key of the HashMap to key in a list and where they are match, I want to get the object from the HashMap and filter it again for example an int field in that object which is greater than 3 for example and sum them in the end. For example if its found 10 case where the list's key and HashMap's key are equal and it's filter those 10 cases and founds 3 case where for example an int field greater then 3 it gives back a sum of these in the end.

Here is my code so far: When i try to print the list of the result of this i get this: java.util.stream.ReferencePipeline$2@70177ecd

somemap.entrySet().stream().filter(e -> aListContainingIds.contains(e.getKey()))
            .map(Map.Entry::getValue)
            .map(n -> n.getTheOtherListFromMatchedValue().stream().filter(n -> n.getAnIntFieldFromObject() > 3))
            .collect(Collectors.toList());

Upvotes: 0

Views: 987

Answers (1)

fps
fps

Reputation: 34470

I think you should use Stream.flatMaptoInt (or Stream.flatMaptoLong) instead of just map:

int total = somemap.entrySet().stream()
    .filter(e -> aListContainingIds.contains(e.getKey()))
    .map(Map.Entry::getValue)
    .flatMapToInt(value -> value.getTheOtherListFromMatchedValue().stream()) 
    .filter(n -> n.getAnIntFieldFromObject() > 3)
    .sum();

In general, flatMapToInt (or flatMap if the stream elements are instances of some class instead of primitives) is to be used when the function you are applying returns another stream, and you want the elements of that stream to be part to the original stream.

At the end, you can get the total with the IntStream.sum method.

Upvotes: 3

Related Questions