[英]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. 不确定如何使用Java 8流。 forEach
? forEach
? peek
? peek
?
if this must be done after the collect
operation, just use forEach
: 如果必须在执行collect
操作之后执行此操作,请使用forEach
:
map.forEach((k, v) -> {...});
if you're only interested in values: 如果您只对值感兴趣:
map.values().forEach(item -> {...});
or only keys: 或仅按键:
map.keySet().forEach(item -> {...});
This will be controversial , but I would use peek()
: 这将引起争议 ,但我将使用peek()
:
myStream.parallel()
.filter(Objects::nonNull)
.peek(item -> item.setDate(item.getOneDate()))
IMO, this use case invalidates many of the arguments against using peek()
for state modification, since it's essentially side-effect free (assuming elements are no longer accessible from the stream source). IMO,此用例使反对使用peek()
进行状态修改的许多参数无效,因为它基本上没有副作用(假定不再可以从流源访问元素)。 It definitely complies with the only strict requirement of non-interference . 它绝对符合不干扰的唯一严格要求。
I would agree with Jigar Joshi . 我同意吉加尔·乔希 ( Jigar Joshi)的观点 。 A map
operation is cleaner. map
操作更加简洁。 And if you have no need for an intermediate object, just return the same one: 如果不需要中间对象,则返回相同的对象:
myStream.parallelStream()
.map(i -> { i.setDate(i.getOneDate()); return i; })
...
That said, I would avoid mutating objects in the middle of a Stream
. 也就是说,我将避免在Stream
的中间对对象进行变异。 It's bad practice. 这是不好的做法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.