Stream(流)是一個來自數(shù)據(jù)源的元素隊列并支持聚合操作
元素是特定類型的對象,形成一個隊列。 - Java中的Stream并不會存儲元素,而是按需計算。
數(shù)據(jù)源,流的來源。 可以是集合,數(shù)組,I/O channel, 產(chǎn)生器generator 等。
聚合操作,類似SQL語句一樣的操作, 比如filter, map, reduce, find, match, sorted等。
和以前的Collection操作不同, Stream操作還有兩個基礎(chǔ)的特征:Pipelining: 中間操作都會返回流對象本身。 這樣多個操作可以串聯(lián)成一個管道, 如同流式風(fēng)格(fluent style)。 這樣做可以對操作進行優(yōu)化, 比如延遲執(zhí)行(laziness)和短路( short-circuiting)。
內(nèi)部迭代: 以前對集合遍歷都是通過Iterator或者For-Each的方式, 顯式的在集合外部進行迭代, 這叫做外部迭代。 Stream提供了內(nèi)部迭代的方式, 通過訪問者模式(Visitor)實現(xiàn)。
Stream操作的三個步驟
- 創(chuàng)建 Stream
集合接口有兩個方法來生成流:
- stream() ? 為集合創(chuàng)建串行流。
- parallelStream() ? 為集合創(chuàng)建并行流。
- 中間操作
一個中間操作鏈,對數(shù)據(jù)源的數(shù)據(jù)進行處理。比如fifter、distinct、limit、skip、map、sorted、
- 終止操作
一旦執(zhí)行終止操作,就執(zhí)行中間操作鏈,并產(chǎn)生結(jié)果。之后,不會再被使用。
比如:match、findFirst、count、max、min、forEach、reduce、collect
創(chuàng)建 Stream
一般我們使用的場景是對列表或數(shù)組操作。通過Collection的方法stream()和parallelStream()獲取。
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
list.stream().forEach(System.out::println);
list.parallelStream().forEach(System.out::println);
中間操作
fifter(Predicate<? super T> predicate)
根據(jù)過濾條件,保留符合條件的元素
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 9);
list.stream().filter(item -> item > 5).forEach(System.out::println);
distinct ()
去重
list.stream().filter(item -> item > 5).distinct().forEach(System.out::println);
limit(long maxSize)
返回前maxSize個元素
list.stream().filter(item -> item > 5).limit(2).forEach(System.out::println);
skip(long n)
調(diào)過前n個
list.stream().filter(item -> item > 5).skip(2).forEach(System.out::println);
sorted()/sorted(Comparator<? super T> comparator)
// 自然排序
list.stream().sorted().forEach(System.out::println);
// 根據(jù)比較器順序排序
list.stream().sorted((a1, a2) -> a2.compareTo(a1)).forEach(System.out::println);
map/flatMap
map(Function<? super T, ? extends R> mapper)
mapToInt(ToIntFunction<? super T> mapper)
mapToDouble(ToDoubleFunction<? super T> mapper)
mapToLong(ToLongFunction<? super T> mapper)
flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
flatMapToInt(Function<? super T, ? extends IntStream> mapper)
flatMapToLong(Function<? super T, ? extends LongStream> mapper)
flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper)
map() 接收一個函數(shù)作為參數(shù),該函數(shù)會被應(yīng)用到每個元素上,并將其映射成一個新的元素
flatMap()接收一個函數(shù)作為參數(shù),將流中的每個值都換成另一個流,然后把所有流連接成一個流
創(chuàng)建一個對象product
public class Product {
private Long id;
private Integer num;
private Double price;
private String name;
public Product() {}
public Product(Long id, Integer num, Double price, String name) {
this.id = id;
this.num = num;
this.price = price;
this.name = name;
}
// get/set省略
}
Product prod1 = new Product(1L, 1, new Double(15.5), "面包");
Product prod2 = new Product(2L, 2, new Double(20), "餅干");
Product prod3 = new Product(3L, 3, new Double(30), "月餅");
List<Product> prodList = Lists.newArrayList(prod1, prod2, prod3);
List<String> nameList = prodList.stream().map(item -> item.getName()).collect(Collectors.toList());
System.out.println(nameList); // [面包, 餅干, 月餅]
Long count = prodList.stream().mapToInt(item -> item.getNum()).count();
System.out.println(count); // 3
Long min = prodList.stream().mapToLong(item -> item.getId()).min().getAsLong();
System.out.println(min); // 1
prodList.stream().mapToDouble(item -> item.getPrice()).forEach(System.out::println);
// 15.5 20.0 30.0
List<String> strList = prodList.stream().flatMap(item -> Arrays.stream(item.getName().split(""))).collect(Collectors.toList());
System.out.println(strList.toString());
// [面, 包, 餅, 干, 月, 餅]
終止操作
終止操作會從流的流水線生成結(jié)果。
anyMatch(Predicate<? super T> predicate);
檢查是否有至少一個能夠滿足條件
Boolean anyMatch = prodList.stream().anyMatch(item -> "面包".equals(item.getName()));
System.out.println("anyMatch="+anyMatch);
allMatch(Predicate<? super T> predicate)
檢查是否所有滿足條件
Boolean allMatch = prodList.stream().allMatch(item -> "面包".equals(item.getName()));
System.out.println("allMatch="+allMatch);
noneMatch
Boolean noneMatch = prodList.stream().noneMatch(item -> "面包".equals(item.getName()));
System.out.println("noneMatch="+noneMatch);
findFirst
返回第一個
findAny
返回任意一個
System.out.println(prodList.stream().filter(item -> item.getNum() < 3).findFirst().get().getId());
System.out.println(prodList.stream().filter(item -> item.getNum() < 3).findAny().get().getId());
count()總數(shù)/min最小數(shù)/max最大數(shù)
Long count = prodList.stream().count();
Integer num = prodList.stream().min((a1, a2) -> a1.getNum().compareTo(a2.getNum())).get().getNum();
Double price = prodList.stream().max((a1, a2) -> a1.getPrice().compareTo(a2.getPrice())).get().getPrice();
System.out.println(count);
System.out.println(num);
System.out.println(price);
forEach
內(nèi)部迭代
reduce
- T reduce(T identity, BinaryOperator<T> accumulator)
可以將流中元素反復(fù)結(jié)合起來,得到一個值,返回 T
- Optional<T> reduce(BinaryOperator<T> accumulator);
將流中元素反復(fù)結(jié)合起來,得到一個值, 返回 Optional<T>
List<Integer> list = Lists.newArrayList(1, 3, 2, 4, 5, 6, 7, 8, 9);
Integer reduce = list.stream().reduce(0, (x, y) -> x+y);
System.out.println(reduce);
// 有可能為null
List<Product> prodList = Lists.newArrayList();
Optional<Integer> reduceOpt = prodList.stream().map(Product::getNum).reduce(Integer::sum);
System.out.println(reduceOpt.isPresent());
collect
將流轉(zhuǎn)化為其他形式,常用的List,Set、Map、Collection
// 轉(zhuǎn)為list
List<String> nameList = prodList.stream().map(item -> item.getName()).collect(Collectors.toList());
// 轉(zhuǎn)為Set
Set<String> nameSet = prodList.stream().map(item -> item.getName()).collect(Collectors.toSet());
// 轉(zhuǎn)為Map
Map<Long, Product> idMap = prodList.stream().collect(Collectors.toMap(Product::getId,Functions.identity()));
// 轉(zhuǎn)為LinkedList
prodList.stream().map(item -> item.getName()).collect(Collectors.toCollection(LinkedList::new));
//統(tǒng)計總數(shù)
Long count = prodList.stream().collect(Collectors.counting());
// 分組
Map<Long, List<Product>> listMap = prodList.stream().collect(Collectors.groupingBy(Product::getId));
// 拼接
String nameJoin = prodList.stream().map(Product::getName).collect(Collectors.joining());