3

I have a set of Objects. I want to filter it based on certain criteria, the ones which meet the criteria, I want to perform some action & then do some more mapping.

Set<Tasks> v1;
Map<V, Long> vC = v1.stream()
                .filter(t -> someCondition(t))
                //for these filtered operations perform some action
                .forEach(t -> t.performAction(summation(t))
                .map(t->summation(t))
                .collect(groupingBy(identity(), counting()));

I get an error at the map Cannot resolve method 'map'. If I remove forEach it works. I know forEach is a terminal operation, but I can't think of alternative.

1 Answer 1

4

EDIT: Today (November 2019) I'm not happy with this answer.

The issue is that the Stream.peek method is not being used correctly. In fact, peek is to be used only for debugging purposes.

And, as @Holger states in the comments section, the summation method is being called twice, which clearly indicates this is not a good answer.

I'm keeping my original answer below as a reminder for myself and others, that sometimes streams are not the best fit.


You could use the peek operation to achieve what you want:

Map<V, Long> vC = v1.stream()
    .filter(t -> someCondition(t))
    .peek(t -> t.performAction(summation(t))
    .map(t->summation(t))
    .collect(groupingBy(identity(), counting()));
Sign up to request clarification or add additional context in comments.

1 Comment

…and the obligatory link. Besides that, this code calculates summation(t) twice, which a shouting for an alternative solution…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.