查看Java java.util.stream包文档,对流使用中遵循的最佳实践产生了疑问.考虑这段代码:
HashMap<Integer,Integer> map = new HashMap<>();
map.put(1,1);
map.put(2,2);
map.put(3,3);
map.put(4,4);
map.keySet().parallelStream().forEach(key -> {
if (key == 3) {
map.put(3,0);
}
});
Run Code Online (Sandbox Code Playgroud)
换句话说,上面的代码可以被认为符合流文档中建议的最佳实践吗?
考虑以下代码:
Function<BigDecimal,BigDecimal> func1 = x -> x;//This could be anything
Function<BigDecimal,BigDecimal> func2 = y -> y;//This could be anything
Map<Integer,BigDecimal> data = new HashMap<>();
Map<Integer,BigDecimal> newData =
data.entrySet().stream().
collect(Collectors.toMap(Entry::getKey,i ->
func1.apply(i.getValue())));
List<BigDecimal> list =
newData.entrySet().stream().map(i ->
func2.apply(i.getValue())).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
基本上我正在做的是使用func1更新HashMap,使用func2应用第二次转换并将第二次更新的值保存在列表中。我以一成不变的方式DID生成新对象newData和list。
我的问题:是否可以将原始HashMap(数据)流一次?
我尝试了这个:
Function<BigDecimal,BigDecimal> func1 = x -> x;
Function<BigDecimal,BigDecimal> func2 = y -> y;
Map<Integer,BigDecimal> data = new HashMap<>();
List<BigDecimal> list = new ArrayList<>();
Map<Integer,BigDecimal> newData =
data.entrySet().stream().collect(Collectors.toMap(
Entry::getKey,i ->
{
BigDecimal newValue = func1.apply(i.getValue());
//SIDE EFFECT!!!!!!!
list.add(func2.apply(newValue));
return newValue;
}));
Run Code Online (Sandbox Code Playgroud)
但是这样做会在列表更新中产生副作用,因此我失去了“不变方式”的要求。