List<String> myList = Arrays.asList("a1", "a2", "a3", "b1", "b2", "c1", "c2");
myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Stream.of() 從一堆對(duì)象中創(chuàng)建 Stream 流。
Stream.of("a1", "a2", "a3", "b1", "b2", "c1", "c2")
.findFirst()
.ifPresent(System.out::println);
取代 for 循環(huán)
IntStream.range(1, 4)
.forEach(System.out::println);
sum() / average()
Arrays.stream(new int[]{1, 2, 3})
.map(n -> 2 * n + 1)
.average()
.ifPresent(System.out::println);
mapToInt() / mapToLong() / mapToDouble
Stream.of("a1", "a2", "a3")
.map(s -> s.substring(1))
.mapToInt(Integer::parseInt)
.max()
.ifPresent(System.out::println);
mapToObj()
IntStream.range(1, 4)
.mapToObj(i -> "a" + i)
.forEach(System.out::println);
組合示例
Stream.of(1.0, 2.0, 3.0)
.mapToInt(Double::intValue)
.mapToObj(i -> "a" + i)
.forEach(System.out::println);
Stream 流的處理是隨著鏈條垂直移動(dòng)的。比如說(shuō),當(dāng) Stream 開始處理第一個(gè)元素時(shí),它實(shí)際上會(huì)執(zhí)行完filter 后,再執(zhí)行 forEach,接著才會(huì)處理第二個(gè)元素。
Stream.of("d2", "a2", "b1", "b3", "c")
.map(s -> {
System.out.println("map: " + s);
return s.toUpperCase();
})
.anyMatch(s -> {
System.out.println("anyMatch: " + s);
return s.startsWith("A");
});
map: d2
anyMatch: D2
map: a2
anyMatch: A2
所以我們改變中間操作的順序,將 filter 移動(dòng)到鏈頭的最開始,就可以大大減少實(shí)際的執(zhí)行次數(shù)。這種小技巧對(duì)于流中存在大量元素來(lái)說(shuō),是非常有用的。
排序,sorted 是水平執(zhí)行的。
Stream.of("d2", "a2", "b1", "b3", "c")
.sorted(String::compareTo)
.forEach(System.out::println);
復(fù)用流的方法
Supplier<Stream<String>> streamSupplier = () -> Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> s.startsWith("a"));
streamSupplier.get().anyMatch(s -> true);
streamSupplier.get().noneMatch(s -> true);
.collect(Collectors.toList())
.collect(Collectors.toSet())
.collect(Collectors.groupingBy(p -> p.age))
.collect(Collectors.averagingInt(p -> p.age))
.collect(Collectors.summarizingInt(p -> p.age)) 全面的統(tǒng)計(jì)信息,摘要收集器計(jì)算出總數(shù)量,總和,最小值,平均值和最大值。
IntSummaryStatistics collect = persons.stream()
.collect(Collectors.summarizingInt(Person::getAge));
System.out.println(collect);
IntSummaryStatistics{count=4, sum=76, min=12, average=19.000000, max=23}