1. stream().map()
示例:对List中的每个数字取平方
public void testMap() {
List<Integer> test = Arrays.asList(1,2,3,4,5);
List<Integer> collect = test.stream()
.map(i->func(i))
.collect(Collectors.toList());
log.info("collect is " +collect);
log.info("test is " + test);
}
private int func(int i) {
return i*i;
}
输出结果:
collect is [1, 4, 9, 16, 25]
test is [1, 2, 3, 4, 5]
可见,map会将stream中的每个数字(1,2,3,4,5)送入函数(func)执行后,将原来的数字替换成了新的函数运算结果。所以map执行完,stream中的内容已经从(1,2,3,4,5)变成了 (1, 4, 9, 16, 25)。当然了,原List test的内容是没有变的。
2. stream().foreach()
依旧取平方
public void testForeach() {
List<Integer> test = Arrays.asList(1,2,3,4,5);
test.stream().forEach(i->func(i));
log.info("test is " + test);
}
private int func(int i) {
return i*i;
}
输出结果
test is [1, 2, 3, 4, 5]
foreach是一个stream的结尾,不像map后还能用collect,foreach之后stream就被消耗完了。foreach就是单纯地把数字送进func执行,就没有然后了,也不再返回什么。