4、Stream API
**Stream APl ( java.util.stream)**把真正的函数式编程风格引入到Java中。这是目前为止对Java类库最好的补充,因为Stream API可以极大提供Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。
Stream是 Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。
使用Stream API对集合数据进行操作,就类似于使用SQL执行的数据库查询。也可以使用Stream API来并行执行操作。简言之,Stream API提供了一种高效且易于使用的处理数据的方式。
4.1 为什么要使用StreamAPI
实际开发中,项目中多数数据源都来自于Mysql,Oracle等。但现在数据源可以更多了,有MongDB,Redis等,而这些NoSQL(非关系型)的数据就需要Java层面去处理。
Stream和 Collection集合的区别:Collection是一种静态的内存数据结构(容器)
,而 Stream是有关计算的
。前者是主要面向内存,存储在内存中,后者主要是面向CPU,通过CPU实现计算。
4.2 Stream特点
Stream到底是什么呢?
是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列
“ 集合讲的是数据,Stream讲的是计算!”
注意:
- Stream自己不会存储元素
- Stream不会改变源对象。相反,他们会返回一个持有结果的新Stream。
- Stream操作是延迟的。这意味着他们会等到需要结果的时候才执行
4.3 执行Stream流程
- 创建 Stream
- 一个数据源(如:集合、数组),获取一个流
- 中间操作
- 一个中间操作,对数据源的数据进行处理
- 终止操作(终端操作)
- 只有执行终止操作,才会执行中间操作链(延迟特性),并产生结果,不会再被使用
4.4 创建Stream对象
- 通过集合 //Collection接口中有默认方法 default Stream stream()
- 会有两种流:1. 顺序流 2.并行流
- 通过数组 //调用Arrays类的 static Stream(T[] array): 返回一个流
- 通过Stream接口的of()方法: //Stream接口中有静态方法public static< T> Stream< T> of(T… values),可直接 接口名.of 调用
- 通过Stream接口,创建无限流: 有两个静态方法 iterate 和 generate (用来造数据)
//创建Stream方式一:通过集合
@Test
public void test1(){
List<Employee> employees = EmployeeData.getEmployees();
// default Stream<E> stream():返回一个顺序流
Stream<Employee> stream = employees.stream();
System.out.println(stream.getClass());//class java.util.stream.ReferencePipeline$Head
// default Stream<E> parallelStream(): 返回一个并行流 底层开启了并行
Stream<Employee> stream1 = employees.parallelStream();
System.out.println(stream1.getClass());//class java.util.stream.ReferencePipeline$Head
}
//创建 Stream方式二:通过数组
@Test
public void test2(){
int[] arr = new int[]{1, 2, 3, 4, 5, 6};
//调用Arrays类的 static <T> Stream(T[] array): 返回一个流
IntStream stream = Arrays.stream(arr);
//注意他会根据传入不同类型的参数,返回不同类型的Stream
Employee e1 = new Employee(1001, "Tom");
Employee e2 = new Employee(1002, "Jerry");
Employee[] arr1 = new Employee[]{e1,e2};
Stream<Employee> stream1 = Arrays.stream(arr1);
}
//创建 Stream 方式三:通过 Stream 的of() 方法
@Test
public void test3(){
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
}
//创建 Stream 方式四:通过Stream接口,创建无限流
@Test
public void test4(){
//迭代
//public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
//遍历前10个偶数
Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);
//生成
//public static<T> Stream<T> generate(Supplier<T> s)
Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
4.5 Stream的中间操作
多个**中间操作
可以连接起来形成一个流水线
,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!
** 而在终止操作时一次性全部处理,称为“惰性求值”
4.5.1 筛选与切片
- Stream< T> filter(Predicate<? super T> predicate); 从流中排除某些元素
- Stream< T> limit(long maxSize);——截断流,使其元素不超过指定数量
- Stream< T> skip(long n); —— 跳过元素,返回一个扔掉了前n各元素的流。若流中元素不足n个,则返回一个空值(啥也没有)
- Stream< T> distinct(); ——筛选(去重),通过流所生成元素的 hashCode() 和 equals() 去除重复元素
代码演示:
List<Employee> list = EmployeeData.getEmployees();
Stream<Employee> stream = list.stream();
System.out.println(stream.getClass());//class java.util.stream.ReferencePipeline$Head
// Stream<T> filter(Predicate<? super T> predicate); 从流中排除某些元素
//中间操作 //终止操作
stream.filter(employee -> employee.getSalary() > 7000).forEach(System.out::println);
System.out.println();
// Stream<T> limit(long maxSize);——截断流,使其元素不超过指定数量
list.stream().limit(3).forEach(System.out::println);
System.out.println();
// Stream<T> skip(long n); —— 跳过元素,返回一个扔掉了前n各元素的流。若流中元素不足n个,则返回一个空值(啥也没有)
list.stream().skip(3).forEach(System.out::println);
System.out.println();
//
list.add(new Employee(1010, "刘强东", 40, 8000));
list.add(new Employee(1010, "刘强东", 40, 8000));
list.add(new Employee(1010, "刘强东", 40, 8000));
list.add(new Employee(1010, "刘强东", 42, 8000));
list.add(new Employee(1010, "刘强东", 40, 8000));
//System.out.println(list);
// Stream<T> distinct(); ——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
list.stream().distinct().forEach(System.out::println);
4.5.2 映射
- < R> Stream< R> map(Function<? super T, ? extends R> mapper);
- // 接收一个函数作为参数,将元素转换为其他形式或提取信息,该函数会被应用到每个元素上,并映射成一个新的元素
// <R> Stream<R> map(Function<? super T, ? extends R> mapper);
// 接收一个函数作为参数,将元素转换为其他形式或提取信息,该函数会被应用到每个元素上,并映射成一个新的元素
List<String> list = Arrays.asList("aa", "bb", "cc", "dd");
//将每个元素转换成大写(映射规则为转换大写)
list.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
//练习:获取员工姓名>3 的员工姓名
List<Employee> employees = EmployeeData.getEmployees();
//提取员工姓名
Stream<String> namesStream = employees.stream().map(e -> e.getName());
//过滤
namesStream.filter(name -> name.length() > 3).forEach(System.out::println);
- // 接收一个函数作为参数,将流中的每个值都添加到另一个流中,成为一个流
- < R> Stream< R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
//需求:将多个流合并成一个流
//使用 map 它会将多各个流嵌套成一个流,类似:{{1,2},{2,3}}
Stream<Stream<Character>> streamStream = list.stream().map(s -> StreamAPITest1.fromStringToStream(s));
streamStream.forEach(stream -> {
stream.forEach(System.out::println);
});
//使用 他会将多个流拆解开,形成一个流 {1,2,1,3}
//flat有扁平的意思,理解为压平它
Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);
characterStream.forEach(System.out::println);
fromStringToStream():
//将字符串转换为对应的Stream的实例
public static Stream<Character> fromStringToStream(String str){
ArrayList<Character> list = new ArrayList<>();
for (Character c : str.toCharArray()){
list.add(c);
}
return list.stream();
}
4.5.3 排序
//sorted()——自然排序 元素(对象)要实现Comparable接口
List<Integer> list = Arrays.asList(12, 54, 89, 21, 20, 14, 44, 90);
list.stream().sorted().forEach(System.out::println);
//sorted(Comparator com)——定制排序
List<Employee> employees = EmployeeData.getEmployees();
employees.stream().sorted(((o1, o2) ->
Integer.compare(o1.getAge(),o2.getAge()))).forEach(System.out::println);
4.6 Stream终止操作
终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List.、Integer、甚至是void 。
流进行了终止操作后,不能再次使用
4.6.1 匹配与查找
List<Employee> employees = EmployeeData.getEmployees();
// count 返回流中的元素的总个数
long count = employees.stream().count();
System.out.println(count);//8
//max(Comparator com) 返回流中的最大值
//练习:返回最高的工资
Optional<Double> maxEmployee = employees.stream().map(employee ->
employee.getSalary()).max(Double::compare);
System.out.println(maxEmployee);//Optional[78974.23]
//min(Comparator com) 返回流中的最小值
//练习:返回工资最低的员工
Optional<Employee> minEmployee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(minEmployee);
System.out.println();
//forEach(Consumer c) 内部迭代
employees.stream().forEach(System.out::println);
//使用集合的遍历操作
employees.forEach(System.out::println);
4.6.2 规约
//T reduce(T identity, BinaryOperator<T> accumulator);
//可以将流中元素反复结合起来,得到一个值。返回
//练习:计算1-10的自然数的和
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = list.stream().reduce(0, Integer::sum);
System.out.println(sum);
//Optional<T> reduce(BinaryOperator<T> accumulator);
//练习2:计算公司所有员工工资的总和
List<Employee> employees = EmployeeData.getEmployees();
Optional<Double> reduce = employees.stream().map(e -> e.getSalary()).reduce(Double::sum);
System.out.println(reduce);//Optional[301763.27]
4.6.3 收集
//collect(Collector c)
//练习1:查找工资大于6000的员工,结果返回一个List或Set
List<Employee> employees = EmployeeData.getEmployees();
List<Employee> employeeList = employees.stream().filter(e ->
e.getSalary() > 6000).collect(Collectors.toList());
employeeList.forEach(System.out::println);
System.out.println(employeeList.getClass());//class java.util.ArrayList
Set<Employee> employeeSet = employees.stream().filter(e ->
e.getSalary() > 6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);
System.out.println(employeeSet.getClass());//class java.util.HashSet