在Java 8中,当我一个接一个地链接方法时,使用流以流水线方式执行操作.
例:
List<Integer> nums = Arrays.asList(1,2,3,4,5,6);
nums.stream().map(x->{
x = x * x;
System.out.println("map1="+x);
return x;
}).map(x->{
x = x * 3;
System.out.println("map2="+x);
return x;
}).forEach(x-> System.out.println("forEach="+x));
Run Code Online (Sandbox Code Playgroud)
输出: -
map1=1
map2=3
forEach=3
map1=4
map2=12
forEach=12
map1=9
map2=27
forEach=27
map1=16
map2=48
forEach=48
map1=25
map2=75
forEach=75
map1=36
map2=108
forEach=108
Run Code Online (Sandbox Code Playgroud)
但是当我在javascript中尝试类似时.结果是不同的.在javascript中,第一个操作完成,然后执行第二个操作.例如: -
var nums = [1,2,3,4,5,6 ];
nums.map(x => {
x = (x * x);
console.log('map1='+x);
return x;})
.map(x => {
x = x * 3;
console.log('map2='+x);
return x;})
.forEach(x=> console.log('forEach='+x));
Run Code Online (Sandbox Code Playgroud)
输出: - …