Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling method on object in Java 8 stream after collecting

Suppose I have this bit of code:

Map<Consumer, Item> map = myStream.parallel()
        .filter(Objects::nonNull)
        .collect(Collectors.toConcurrentMap(e->e,
                e->e, mergeFunction));

What I want to do is call a method on each object of the stream after collecting is done.

For example,

item.setDate(item.getOneDate());

Before the code done sequentially looped through items, put into a map, and at the very end called a bit of the code like the one above, setting a 'date'.

while(iterator.hasNext()) {
   Item blah = iterator.next();
   ....
   // code for putting into map
   ...
   blah.setDate(blah.getOneDate());
}

Not sure how to do this with Java 8 streams. forEach? peek?

like image 987
SS' Avatar asked Feb 14 '26 03:02

SS'


1 Answers

if this must be done after the collect operation, just use forEach:

map.forEach((k, v) -> {...});

if you're only interested in values:

map.values().forEach(item -> {...});

or only keys:

map.keySet().forEach(item -> {...});
like image 193
Ousmane D. Avatar answered Feb 15 '26 17:02

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!