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.

user1692342
  • 5,007
  • 11
  • 69
  • 128

1 Answers1

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()));
fps
  • 33,623
  • 8
  • 55
  • 110
  • 2
    …and [the obligatory link](http://stackoverflow.com/q/33635717/2711488). Besides that, this code calculates `summation(t)` twice, which a shouting for an alternative solution… – Holger Mar 29 '17 at 09:18