从0开始学习Stream

266 阅读2分钟

流Stream是Java8新增的一个特性。它专注于对集合对象的高效的聚合操作。它支持串行和并行2中聚合操作。使用Stream的好处在于让程序更高效的执行和提高了代码的可读性。

流的顶级接口是BaseStream。它提供了一个迭代器方法,和一个可分割迭代器方法,判断是否是并行和串行的2个方法,以及2个关闭资源的方法。


在这里我们先来了解下可分割迭代器。它是用来遍历和分割元素源的一个对象,元素源可以是一个数组,一个集合。它在遍历元素的时候可以有2种方式,一是单独的遍历,另一种是批量的遍历。


它可以把一些元素分割出来作为另一个可分割迭代器,用于并行的操作。需要注意的是一个可分割迭代器只在单个批量计算中是有用的。

下面是一些方法的使用。

1. boolean allMatch(Predicate<? super T> predicate);

Stream<Integer> stream = Stream.of(1, 2, 5);
boolean res = stream.allMatch(num -> num > 3);
System.out.println(res);// return false

2. boolean anyMatch(Predicate<? super T> predicate);

Stream<Integer> stream = Stream.of(1, 2, 5);
boolean res = stream.anyMatch( num -> num > 3);
System.out.println(res);// return true

3. boolean allMatch(Predicate<? super T> predicate);

Stream<Integer> stream = Stream.of(1, 2, 5);
boolean res = stream.noneMatch( num -> num > 9);
System.out.println(res);// return true

4. long count();

Stream<Integer> stream = Stream.of(1, 2, 5);
long count = stream.count();
System.out.println(count);// return 3

5. Stream<T> distinct();
Stream<Integer> stream = Stream.of(1, 2, 5, 2);
stream.distinct().forEach(e -> System.out.println(e));//return 1 2 5

6. Stream<T> filter(Predicate<? super T> predicate);

Stream<Integer> stream = Stream.of(1, 2, 5);
stream.filter( num -> num >= 2).forEach(System.out::println);// return 2 5


今天就先介绍这6个简单的方法吧。下一篇文章会继续介绍Stream中的其他常用方法。