maphtml
final List<Integer> numbers = Arrays.asList(1, 2, 3, 4); final List<Integer> doubleNumbers = numbers.stream() .map(number -> number * 2) .collect(Collectors.toList());
結果:[2, 4, 6, 8]sql
也能夠搞成其餘的類型,初始List是Integer,也能夠變成Stringspa
final List<Integer> numbers = Arrays.asList(1, 2, 3, 4); final List<String> numberIndex = numbers.stream() .map(number -> "#" + number) .collect(Collectors.toList());
結果:[#1, #2, #3, #4].net
reducecode
1.不提供初始值的reduce,返回值是Optional,表示可能爲空,使用orElseGet能夠返回一個null時的默認值htm
final List<Integer> numbers = Arrays.asList(1, 2, 3, 4); final Optional<Integer> sum = numbers.stream() .reduce((a, b) -> a + b); sum.orElseGet(() -> 0);
結果:10blog
這裏的(a, b) -> a + b的類型實際上是BinaryOperator,它接受兩個類型相同的參數io
當把numbers改成Arrays.asList()時,結果爲0。class
2.使用初始值的reduce,由於提供了初始值,因此返回值再也不是Optionalstream
final List<Integer> numbers = Arrays.asList(1, 2, 3, 4); final Integer sum = numbers.stream() .reduce(0, (a, b) -> a + b);
結果:10
http://blog.csdn.net/kiwi_coder/article/details/31771475
http://www.cnblogs.com/shinn-sjl/p/5781468.html