似乎这个问题应该已经有了答案,但我找不到重复的答案。
无论如何,我想知道社区如何看待这样的Stream.map用例?
Wrapper wrapper = new Wrapper();
list.stream()
.map( s -> {
wrapper.setSource(s);
return wrapper;
} )
.forEach( w -> processWrapper(w) );
public static class Source {
private final String name;
public Source(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public static class Wrapper {
private Source source = null;
public void setSource(Source source) {
this.source = source;
}
public String getName() {
return source.getName();
}
}
public void processWrapper(Wrapper wrapper) {
}
我不是这种用法的忠实粉丝,map但它可能有助于在处理大型流时提高性能并避免Wrapper为每个Source.
这肯定有其局限性,例如对于并行流和终端操作(如collect.
更新 - 问题不在于“如何做”,而是“我可以这样做吗”。例如,我可以有一个仅适用于 Wrapper 的代码,我想在其中调用它,forEach但又想避免为每个Source元素创建它的新实例。
基准测试结果
使用可重复使用的包装纸显示大约8倍的改进-
基准 (N) 模式 Cnt 得分误差单位
BenchmarkTest.noReuse 10000000 平均 5 870,253 ± 122,495 毫秒/操作
BenchmarkTest.withReuse 10000000 平均 5 113.694 ± 2.528 毫秒/操作
呼如林
米脂
LEATH
相关分类