什么是流
流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,他不是数据结构并不保存数据,他的主要目的在于计算
如何生成流
生成流的方式主要有五种
1、通过集合生成,应用中最常用的一种
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Stream<Integer> stream = list.stream();
通过集合的stream生成流
2、通过数组生成
int[] ints = new int[]{1, 2, 3, 4, 5, 6, 7, 8};
IntStream intStream = Arrays.stream(ints);
通过Arrays.stream方法生成流,并且该方法生成的流是数值流【即IntStream】而不是 Stream。补充一点使用数值流可以避免计算过程中拆箱装箱,提高性能。
Stream API提供了mapToInt、mapToDouble、mapToLong三种方式将对象流【即Stream 】转换成对应的数值流,同时提供了boxed方法将数值流转换为对象流
3、通过值生成
Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5, 6);
4、通过文件生成
try {
Stream<String> lines = Files.lines(Paths.get("/pa.txt"), Charset.defaultCharset());
} catch (IOException e) {
e.printStackTrace();
}
通过Files.line方法得到一个流,并且得到的每个流是给定文件中的一行
5、通过函数生成 提供了iterate和generate两个静态方法从函数中生成流
iterator
Stream<Integer> stream1 = Stream.iterate(0, n -> n + 2).limit(5);
iterate方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为iterator生成的流为无限流,通过limit方法对流进行了截断,只生成5个偶数
generator
Stream<Double> stream2 = Stream.generate(Math::random).limit(5);
generate方法接受一个参数,方法参数类型为Supplier ,由它为流提供值。generate生成的流也是无限流,因此通过limit对流进行了截断
流的操作类型
中间操作
一个流可以后面跟随零个或多个中间操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的,仅仅调用到这类方法,并没有真正开始流的遍历,真正的遍历需等到终端操作时,常见的中间操作有下面即将介绍的filter、map等
filter筛选
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,9,8,5);
list.stream().filter(i -> i > 3);
通过使用filter方法进行条件筛选,filter的方法参数为一个条件
distinct去除重复元素
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,9,8,5);
list.stream().distinct();
通过distinct方法快速去除重复的元素
limit返回指定流个数
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,9,8,5);
list.stream().limit(5);
通过limit方法指定返回流的个数,limit的参数值必须>=0,否则将会抛出异常
skip跳过流中的元素
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,9,8,5);
list.stream().skip(6);
通过skip方法跳过流中的元素,上述例子跳过前两个元素,所以打印结果为2,3,4,5,skip的参数值必须>=0,否则将会抛出异常
map流映射
所谓流映射就是将接受的元素映射成另外一个元素
List<String> stringList =Arrays.asList("Java 8","张三","Ancaots","18");
Stream<Integer> stream3 = stringList.stream().map(String::length);
通过map方法可以完成映射,该例子完成中String -> Integer的映射,对象通过map方法完成了对象->String的映射
flatMap流转换
将一个流中的每个值都转换为另一个流
List<String> stringList =Arrays.asList("Java 8","张三","Ancaots","18");
stringList.stream().map(s -> s.split(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
map(w -> w.split(" "))的返回值为 Stream<String[]>,我们想获取 Stream,可以通过flatMap方法完成Stream ->Stream 的转换
元素匹配
allMatch匹配所有
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,9,8,5);
if (list.stream().allMatch(i -> i > 6)) {
System.out.println("值都大于6");
}
anyMatch匹配其中一个
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,9,8,5);
if (list.stream().anyMatch(i -> i > 6)) {
System.out.println("存在大于6的值");
}
noneMatch全部不匹配
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9,9,8,5);
if (list.stream().noneMatch(i -> i > 6)) {
System.out.println("值都小于6");
}
终端操作
一个流有且只能有一个终端操作,当这个操作执行后,流就被关闭了,无法再被操作,因此一个流只能被遍历一次,若想在遍历需要通过源数据在生成流。终端操作的执行,才会真正开始流的遍历。如下面即将介绍的count、collect等
统计流中元素个数
通过count
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 5);
Long result = list.stream().count();
通过使用count方法统计出流中元素个数
通过counting
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 5);
Long result = list.stream().collect(Collectors.counting());
最后一种统计元素个数的方法在与collect联合使用的时候特别有用
查找
findFirst查找第一个
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 5);
Optional<Integer> result = list.stream().filter(i -> i > 6).findFirst();
通过findFirst方法查找到第一个大于三的元素并打印
findAny随机查找一个
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 5);
Optional<Integer> result = list.stream().filter(i -> i > 6).findAny();
通过findAny方法查找到其中一个大于三的元素并打印,因为内部进行优化的原因,当找到第一个满足大于三的元素时就结束,该方法结果和findFirst方法结果一样。提供findAny方法是为了更好的利用并行流,findFirst方法在并行上限制更多
reduce将流中的元素组合起来
如我们对一个集合中的值进行求和
int sum = list.stream().reduce(0,(a,b)->(a+b));
// 或者
int sum = list.stream().reduce(0,Integer::sum);
reduce接受两个参数,一个初始值这里是0,一个 BinaryOperatoraccumulator
来将两个元素结合起来产生一个新值,
另外reduce方法还有一个没有初始化值的重载方法
获取流中最小最大值
通过min/max获取最小最大值
List<Dish> dishList = new ArrayList<>();
Optional<Integer> min = dishList.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional<Integer> max = dishList.stream().map(Dish::getCalories).max(Integer::compareTo);
// 或
Optional<Integer> min = dishList.stream().mapToInt(Dish::getCalories).min();
Optional<Integer> max = dishList.stream().mapToInt(Dish::getCalories).max();
min获取流中最小值,max获取流中最大值,方法参数为 Comparator<?superT>comparator
通过minBy/maxBy获取最小最大值
List<Dish> dishList = new ArrayList<>();
Optional<Integer> min = dishList.stream().map(Dish::getCalories).collect(Collectors.minBy(Integer::compareTo));
Optional<Integer> max = dishList.stream().map(Dish::getCalories).collect(Collectors.minBy(Integer::compareTo));
minBy获取流中最小值,maxBy获取流中最大值,方法参数为 Comparator<?superT>comparator
通过reduce获取最小最大值
List<Dish> dishList = new ArrayList<>();
Optional<Integer> min = dishList.stream().map(Dish::getCalories).reduce(Integer::compareTo);
Optional<Integer> max = dishList.stream().map(Dish::getCalories).reduce(Integer::compareTo);
求和
通过summingInt
List<Dish> dishList = new ArrayList<>();
int sum = dishList.stream().collect(Collectors.summingInt(Dish::getCalories));
通过sum
List<Dish> dishList = new ArrayList<>();
int sum = dishList.stream().mapToInt(Dish::getCalories).sum();
在上面求和、求最大值、最小值的时候,对于相同操作有不同的方法可以选择执行。可以选择collect、reduce、min/max/sum方法,推荐使用min、max、sum方法。因为它最简洁易读,同时通过mapToInt将对象流转换为数值流,避免了装箱和拆箱操作
通过averagingInt求平均值
List<Dish> dishList = new ArrayList<>();
OptionalDouble avg = dishList.stream().mapToInt(Dish::getCalories).average();
double average = dishList.stream().collect(Collectors.averagingInt(Dish::getCalories));
如果数据类型为double、long,则通过averagingDouble、averagingLong方法进行求平均
通过summarizingInt同时求总和、平均值、最大值、最小值
IntSummaryStatistics intSummaryStatistics = dishList.stream().collect(Collectors.summarizingInt(Dish::getCalories));
double avg = intSummaryStatistics.getAverage(); // 求平均
int max = intSummaryStatistics.getMax(); // 求最大值
int min = intSummaryStatistics.getMin(); // 求最小值
long sum = intSummaryStatistics.getSum();// 求和
如果数据类型为double、long,则通过summarizingDouble、summarizingLong方法
通过foreach进行元素遍历
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 5);
list.stream().forEach(System.out::println);
jdk8之后遍历元素来的更为方便,原来的for-each直接通过foreach方法就能实现了
返回集合
List<Dish> dishList = new ArrayList<>();
List<String> strings = dishList.stream().map(Dish::getName).collect(Collectors.toList());
Set<String> set = dishList.stream().map(Dish::getName).collect(Collectors.toSet());
通过joining拼接流中的元素
List<Dish> dishList = new ArrayList<>();
String result = dishList.stream().map(Dish::getName).collect(Collectors.joining(","));
默认如果不通过map方法进行映射处理拼接的toString方法返回的字符串,joining的方法参数为元素的分界符,如果不指定生成的字符串将是一串的,可读性不强
通过groupingBy进行分组
List<Dish> dishList = new ArrayList<>();
Map<Integer,List<Dish>> map = dishList.stream().collect(Collectors.groupingBy(Dish::getType));
在collect方法中传入groupingBy进行分组,其中groupingBy的方法参数为分类函数。还可以通过嵌套使用
groupingBy进行多级分类
Map<Integer, Map<Object, List<Dish>>> result = dishList.stream().collect(Collectors.groupingBy(Dish::getType,Collectors.groupingBy(dish->{
if (dish.getCalories()<=400) return "0";
else if (dish.getCalories()<=700) return "1";
else return "2";
})));
通过partitioningBy进行分区
分区是特殊的分组,它分类依据是true和false,所以返回的结果最多可以分为两组
Map<Boolean, List<Dish>> result = dishList.stream().collect(Collectors.partitioningBy(Dish::isVegetarian));
等同于
Map<Boolean, List<Dish>> result = dishList.stream().collect(Collectors.groupingBy(Dish::isVegetarian));
这个例子可能并不能看出分区和分类的区别,甚至觉得分区根本没有必要,换个明显一点的例子:
Map<Boolean, List<Integer>> result = list.stream().collect(Collectors.partitioningBy(i -> i < 3));
返回值的键仍然是布尔类型,但是它的分类是根据范围进行分类的,分区比较适合处理根据范围进行分类