1 Stream概述
什么是Stream
?
Stream
将要处理的元素集合看作一种流,在流的过程中,借助Stream API
对流中的元素进行操作,比如:筛选、排序、聚合等。
Stream
可以由数组或集合创建,对流的操作分两种:
- 中间操作:每次返回一个新的流,可以有多个。
- 终端操作:每个流只能进行一次终端操作,终端操作结束后流无法再次使用。终端操作会产生一个新的集合或或值。
Stream
特性:
- stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。
- stream不会改变数据源,一般会产生一个新的集合或值。
- stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。
2 Stream的创建
//将集合转换为Stream流
List<Integer> list =Arrays.asList(1,2,3,4,5);
Stream<Integer> stream =list.stream();
//将数组转换为Stream流,使用Stream的静态方法
String str[] ={"a","b","c"};
Stream<String> stream1 =Stream.of(str);
//使用java.util.Arrays.stream(T[] array)方法用数组创建流
Stream<String> stringStream=Arrays.stream(str);
3 Stream的使用
测试用到的实体类
private String name; // 姓名
private int salary; // 薪资
private int age; // 年龄
private String sex; //性别
private String area; // 地区
// 构造方法
public Person(String name, int salary, int age,String sex,String area) {
this.name = name;
this.salary = salary;
this.age = age;
this.sex = sex;
this.area = area;
}
//get和set方法
用到的list集合
List<Person> personList = new ArrayList<Person>();
personList.add(new Person("Tom", 8900, 18,"male", "New York"));
personList.add(new Person("Jack", 7000, 20,"male", "Washington"));
personList.add(new Person("Lily", 7800, 22,"female", "Washington"));
personList.add(new Person("Anni", 8200, 21,"female", "New York"));
personList.add(new Person("Owen", 9500, 18,"male", "New York"));
personList.add(new Person("Alisa", 7900, 23,"female", "New York"));
3.1 遍历、匹配、筛选
Stream
中的元素是以Optional
类型存在的
Optional
类是一个可以为null
的容器对象。如果值存在则isPresent()
方法会返回true
,调用get()
方法会返回该对象。
//遍历符大于2的元素
list.stream().filter(x->x>2).forEach(System.out::println);
//匹配第一个
Optional<Integer> first = list.stream().filter(x->x>2).findFirst();
//匹配任意(适用任意)
Optional<Integer> any = list.parallelStream().filter(x -> x > 2).findAny();
//是否包含指定元素
boolean b = list.stream().anyMatch(x -> x > 2);
System.out.println(first.get());
System.out.println(any.get());
System.out.println(b);
//结果
3
4
5
3
3
true
3.2 聚合(max,min,count)
用到java8新特性:方法引用
双冒号(
::
)操作符是 Java 中的方法引用。 当们使用一个方法的引用时,目标引用放在::
之前,目标引用提供的方法名称放在::
之后,即目标引用::方法
,eg:Comparator c = (Person p1, Person p2) -> p1.getAge().compareTo(p2.getAge()); Comparator c = Comparator.comparing(Person::getAge);
List<String> list = Arrays.asList("abcd","asdsgfd","sdfs","a");
List<Integer> integers =Arrays.asList(1,2,3,4,5,33,23);
//获取list中最长字符串
Optional<String> max = list.stream().max(Comparator.comparing(String::length));
//获取list中最短字符串
Optional<String> min = list.stream().min(Comparator.comparing(String::length));
//获取集合中大于6的个数
long count = integers.stream().filter(x -> x > 6).count();
System.out.println(max.get());
System.out.println(min.get());
System.out.println(count);
//结果
asdsgfd
a
2
3.3 映射 (map/flatmap)
映射:就是将一个流的元素按照一定的映射规则映射到另一个流中,分为map
和flatmap
map
:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新元素。flatmap
:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成另一个流。
String[] str={"aaaa","bbb","vvvv"};
List<Integer> list =Arrays.asList(1,2,3,4,4,34,12);
//将集合中小写转换为大写
List<String> collect = Arrays.stream(str).map(String::toUpperCase).collect(Collectors.toList());
//给集合中元素+3
List<Integer> collect1 = list.stream().map(x -> x + 3).collect(Collectors.toList());
System.out.println(collect);
System.out.println(collect1);
//结果
[AAAA, BBB, VVVV]
[4, 5, 6, 7, 7, 37, 15]
//将员工工资都加1000,不改变原本集合数据
List<Person> collect = personList.stream().map(person -> {
Person person1 = new Person(person.getName(), 0, 0, null, null);
person1.setSalary(person.getSalary() + 1000);
return person1;
}).collect(Collectors.toList());
System.out.println(collect.get(0).getName()+"---"+collect.get(0).getSalary());
System.out.println(personList.get(0).getName()+"---"+personList.get(0).getSalary());
//改变
List<Person> collect1 = personList.stream().map(person -> {
person.setSalary(person.getSalary() + 1000);
return person;
}).collect(Collectors.toList());
System.out.println(collect.get(0).getName()+"---"+collect.get(0).getSalary());
System.out.println(personList.get(0).getName()+"---"+personList.get(0).getSalary());
//结果
Tom---9900
Tom---8900
Tom---9900
Tom---9900
List<String> stringList = Arrays.asList("c,a,s,d","q,e,e,r");
List<String> collect2 = stringList.stream().flatMap(s -> {
String[] spilt = s.split(",");
//将每个元素转换成一个流
Stream<String> stream = Arrays.stream(spilt);
return stream;
}).collect(Collectors.toList());
System.out.println(collect2);
3.4 收集 collect
collect
主要依赖java.util.stream.Collectors
类内置的静态方法。
3.4.1 归集(toList/toSet/toMap)
因为流不存储数据,在流处理完成后需要将流中的数据收集到一个新的集合中,toList
、toSet
和toMap
比较常用,另外还有toCollection
、toConcurrentMap
等复杂一些的用法。
3.4.2 统计
Collectors
提供了一系列用于数据统计的静态方法:
计数:count
平均值:averagingInt
、averagingLong
、averagingDouble
最值:maxBy
、minBy
求和:summingInt
、summingLong
、summingDouble
统计以上所有:summarizingInt
、summarizingLong
、summarizingDouble
//求总数
Long collect = personList.stream().collect(Collectors.counting());
//求平均工资
Double collect1 = personList.stream().collect(Collectors.averagingDouble(x -> x.getSalary()));
Double collect2 = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
//求最高工资
Optional<Integer> collect3 = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
//求之和
Integer collect4 = personList.stream().collect(Collectors.summingInt(Person::getSalary));
//统计所有信息
DoubleSummaryStatistics collect5 = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
System.out.println("总数:"+collect);
System.out.println("平均工资:"+collect1);
System.out.println("平均工资:"+collect2);
System.out.println("最高工资:"+collect3.get());
System.out.println("和:"+collect4);
System.out.println("所有:"+collect5);
//结果
总数:6
平均工资:8216.666666666666
平均工资:8216.666666666666
最高工资:9500
和:49300
所有:DoubleSummaryStatistics{count=6, sum=49300.000000, min=7000.000000, average=8216.666667, max=9500.000000}
3.5 排序
sorted,中间操作。有两种排序:
- sorted():自然排序,流中元素需实现Comparable接口
- sorted(Comparator com):Comparator排序器自定义排序
//按工资升序
List<String> collect = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
//按工资降序
List<String> collect1 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());
//先按工资在按年龄升序
List<String> collect2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());
System.out.println(collect);
System.out.println(collect1);
System.out.println(collect2);
//结果
[Jack, Lily, Alisa, Tom, Anni, Owen]
[Owen, Tom, Anni, Alisa, Jack, Lily]
[Jack, Lily, Alisa, Tom, Anni, Owen]
3.6 提取/组合
流也可以合并、去重、限制、跳过等操作。
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
//concat:合并两个流 distinct:去重
List<String> collect = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
// limit:限制从流中获得前n个数据
List<Integer> collect1 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
// skip:跳过前n个数据
List<Integer> collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());
System.out.println(collect);
System.out.println(collect1);
System.out.println(collect2);
//结果
[a, b, c, d, e, f, g]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
[3, 5, 7, 9, 11]