概述
作用
使用StreamAPI对集合数据进行操作,就类似于使用SQL执行的数据库查询。
Stream和Collection集合的区别:Collection是一种静态的内存数据结构,而Stream是有关计算的,前置主要是面向内存,存储在内存中,后者主要是面向CPU,通过CPU实现计算。
什么是Stream
Stream是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
集合讲的是数据,Stream讲的是计算
注意:
- Stream自己不会存储元素。
- Stream不会改变源对象。相反,他们会返回一个持有结果的新的Stream。
- Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
Stream的三个步骤
- 创建Stream
从一个数据源(如:集合、数组),获取一个流 - 中间操作
一个中间操作链,对数据源的数据进行处理 - 终止操作(终端操作)
一旦执行终止操作,就执行中间操作连,并产生结果。之后这个被操作的Stream不可再被使用
Stream的实例化
方式一:通过集合
List<Employee> employees = Employee.getEmployees();
// default Stream<E> stream():返回一个顺序流
Stream<Employee> stream = employees.stream();
// default Stream<E> parallelStream():返回一个并行流
Stream<Employee> parallelStream = employees.parallelStream();
方式二:通过数组
IntStream intStream = Arrays.stream(new int[]{1, 2, 3, 4});
Employee employee = new Employee(1001, "郭富城");
Employee employee1 = new Employee(1002, "黎明");
Employee [] employee2 = new Employee[]{employee,employee1};
Stream<Employee> employeeStream = Arrays.stream(employee2);
方式三:通过Stream的of()
Stream<Employee> employee3 = Stream.of(employee, employee1);
方式四:创建无限流
//迭代
//遍历前10个偶数
Stream.iterate(0,n -> n+2).limit(10).forEach(System.out::println);
//生成
Stream.generate(Math::random).limit(10).forEach(System.out::println);
Stream的中间操作
筛选与切片
filter(Predicate p) 从流中过滤某些元素
limit(n) 截断流,使其元素不超过给定数量
skip(n) 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流,与limit(n)互补
distinct() 筛选,通过流所生成元素的hashCode()和equals()去除重复元素
List<Employee> employees = Employee.getEmployees();
Stream<Employee> stream = employees.stream();
//filter(Predicate p) 从流中过滤某些元素
stream.filter(e -> e.getSalary() > 6000).forEach(System.out::println);
System.out.println("************************************");
//limit(n) 截断流,使其元素不超过给定数量
employees.stream().limit(5).forEach(System.out::println);
System.out.println("************************************");
//skip(n) 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流,与limit(n)互补
employees.stream().skip(5).forEach(System.out::println);
System.out.println("************************************");
//distinct() 筛选,通过流所生成元素的hashCode()和equals()去除重复元素
employees.add(new Employee(1010,"周杰伦",84874));
employees.add(new Employee(1010,"周杰伦",84874));
employees.add(new Employee(1010,"周杰伦",84874));
employees.add(new Employee(1010,"周杰伦",84874));
employees.stream().distinct().forEach(System.out::println);
映射
map(Function f)接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素
flatMap(Function f)接收一个函数作为参数,将流中的每个值都转换成另一个流,然后把所有流连接成一个流
map()和flatMap()的区别参考list的add()和addAll()
//获取姓名长度大于2的员工的姓名
List<Employee> employees = Employee.getEmployees();
employees.stream()
.filter(employee -> employee.getName().length() > 2)
.map(Employee::getName).forEach(System.out::println);
List<String> strings = Arrays.asList("aa", "bb", "cc", "dd");
strings.stream().flatMap(StreamAPITest::stringToCharacter).forEach(System.out::println);
public static Stream<Character> stringToCharacter(String string){
ArrayList<Character> characters = new ArrayList<>();
for (Character character : string.toCharArray()){
characters.add(character);
}
return characters.stream();
}
排序
sorter() 自然排序
sorter(Comparator com) 定制排序
List<Employee> employees = Employee.getEmployees();
employees.stream().sorted().forEach(System.out::println);
System.out.println("************************************");
employees.stream().sorted((e1,e2) -> Double.compare(e1.getSalary(),e2.getSalary()))
.forEach(System.out::println);
Stream的终止操作
匹配与查找
//allMatch(Predicate p)检查是否匹配所有元素
//anyMatch(Predicate p)检查是否至少匹配一个元素
//noneMatch(Predicate p)检查时候没有匹配元素
//findFirst返回第一个元素
//findAny返回当前流中的任意元素
//count返回流中元素的总个数
//max(Comparator c)返回流中最大值
//min(Comparator c)返回流中最小值
//forEach(Consumer c)内部迭代
List<Employee> employees = Employee.getEmployees();
//allMatch(Predicate p)检查是否匹配所有元素
boolean allMatch = employees.stream().allMatch(employee -> employee.getSalary() > 4000);
System.out.println(allMatch);
//anyMatch(Predicate p)检查是否至少匹配一个元素
boolean anyMatch = employees.stream().anyMatch(employee -> employee.getSalary() > 9000);
System.out.println(anyMatch);
//noneMatch(Predicate p)检查时候没有匹配元素
boolean noneMatch = employees.stream().noneMatch(employee -> employee.getSalary() > 10000);
System.out.println(noneMatch);
//findFirst返回第一个元素
Optional<Employee> employee = employees.stream().findFirst();
System.out.println(employee);
//findAny返回当前流中的任意元素
Optional<Employee> optionalEmployee = employees.parallelStream().findAny();
System.out.println(optionalEmployee);
//count返回流中元素的总个数
long count = employees.stream().count();
System.out.println(count);
//max(Comparator c)返回流中最大值
Optional<Employee> max = employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(max.get().getSalary());
//min(Comparator c)返回流中最小值
Optional<Employee> min = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(min.get().getSalary());
//forEach(Consumer c)内部迭代
规约
因为经常和map()连用,所以常说map-reduce
reduce(T identity,BinaryOperator)可以将流中元素反复结合起来,得到一个值。返回T
reduce(BinaryOperator)可以将流中元素反复结合起来,得到一个值。返回Optional
int [] ints = new int[10];
//reduce(T identity,BinaryOperator)可以将流中元素反复结合起来,得到一个值。返回T
for (int i = 0; i <10 ; ) {
ints[i] = ++i;
}
int reduce = Arrays.stream(ints).reduce(0,Integer::sum);
System.out.println(reduce);
//reduce(BinaryOperator)可以将流中元素反复结合起来,得到一个值。返回Optional<T>
List<Employee> employees = Employee.getEmployees();
Optional<Double> optionalDouble =
employees.stream().map(Employee::getSalary).reduce(Double::sum);
optionalDouble.ifPresent(System.out::println);
收集
collect(Collector c)将流转换为其他形式。接收一个Collector接口的实现,用于给Stream中元素做汇总的方法
List<Employee> employees = Employee.getEmployees();
List<Employee> employeeList = employees.stream().filter(employee -> employee.getSalary() > 6000).collect(Collectors.toList());
employeeList.forEach(System.out::println);
System.out.println("************************************");
Set<Employee> employeeSet = employees.stream().filter(employee -> employee.getSalary() > 6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);