jdk8-stream的api
Posted zhulibin2012
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jdk8-stream的api相关的知识,希望对你有一定的参考价值。
1.stream流的概念
1.流的创建
//1. 创建 Stream @Test public void test1(){ //1. Collection 提供了两个方法 stream() 与 parallelStream() List<String> list = new ArrayList<>(); Stream<String> stream = list.stream(); //获取一个顺序流 Stream<String> parallelStream = list.parallelStream(); //获取一个并行流 //2. 通过 Arrays 中的 stream() 获取一个数组流 Integer[] nums = new Integer[10]; Stream<Integer> stream1 = Arrays.stream(nums); //3. 通过 Stream 类中静态方法 of() Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6); //4. 创建无限流 //迭代 Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10); stream3.forEach(System.out::println); //截断 Stream<Double> stream4 = Stream.generate(Math::random).limit(2); stream4.forEach(System.out::println); }
2.中间操作
package com.atguigu.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.stream.Stream; import org.junit.Test; /* * 一、Stream API 的操作步骤: * * 1. 创建 Stream * * 2. 中间操作 * * 3. 终止操作(终端操作) */ public class TestStreamaAPI { //1. 创建 Stream @Test public void test1(){ //1. Collection 提供了两个方法 stream() 与 parallelStream() List<String> list = new ArrayList<>(); Stream<String> stream = list.stream(); //获取一个顺序流 Stream<String> parallelStream = list.parallelStream(); //获取一个并行流 //2. 通过 Arrays 中的 stream() 获取一个数组流 Integer[] nums = new Integer[10]; Stream<Integer> stream1 = Arrays.stream(nums); //3. 通过 Stream 类中静态方法 of() Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6); //4. 创建无限流 //迭代 Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10); stream3.forEach(System.out::println); //截断 Stream<Double> stream4 = Stream.generate(Math::random).limit(2); stream4.forEach(System.out::println); } //2. 中间操作 List<Employee> emps = Arrays.asList( new Employee(102, "李四", 59, 6666.66), new Employee(101, "张三", 18, 9999.99), new Employee(103, "王五", 28, 3333.33), new Employee(104, "赵六", 8, 7777.77), new Employee(104, "赵六", 8, 7777.77), new Employee(104, "赵六", 8, 7777.77), new Employee(105, "田七", 38, 5555.55) ); /* 筛选与切片 filter——接收 Lambda , 从流中排除某些元素。 limit——截断流,使其元素不超过给定数量。 skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补 distinct——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素 */ //内部迭代:迭代操作 Stream API 内部完成 @Test public void test2(){ //所有的中间操作不会做任何的处理 Stream<Employee> stream = emps.stream() .filter((e) -> { System.out.println("测试中间操作"); return e.getAge() <= 35; }); //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值” stream.forEach(System.out::println); } //外部迭代 @Test public void test3(){ Iterator<Employee> it = emps.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } @Test public void test4(){ emps.stream() .filter((e) -> { System.out.println("短路!"); // && || return e.getSalary() >= 5000; }).limit(3) .forEach(System.out::println); } @Test public void test5(){ emps.parallelStream() .filter((e) -> e.getSalary() >= 5000) .skip(2) .forEach(System.out::println); } @Test public void test6(){ emps.stream() .distinct() .forEach(System.out::println); } }
3.映射
//2. 中间操作 /* 映射 map——接收 Lambda , 将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。 flatMap——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流 //map与flatMap区别: map: 将集合中的每个元素执行传入的方法,返回的是Stream<String>,所以返回值是一个Stream<Stream<String>> flatMap: 则是将list中的每个元素执行方法后,返回值本身,并将所有值返回,得到的最终结果是Stream<String> */ @Test public void test1(){ Stream<String> str = emps.stream() .map((e) -> e.getName()); System.out.println("-------------------------------------------"); List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee"); Stream<String> stream = strList.stream() .map(String::toUpperCase); //将strlist中的每个值转换成大写 stream.forEach(System.out::println); Stream<Stream<Character>> stream2 = strList.stream() .map(TestStreamAPI1::filterCharacter); stream2.forEach((sm) -> { sm.forEach(System.out::println); }); System.out.println("---------------------------------------------"); Stream<Character> stream3 = strList.stream() .flatMap(TestStreamAPI1::filterCharacter); stream3.forEach(System.out::println); }
4.排序
/*排序: sorted()——自然排序(实现comparable接口,例如String类) sorted(Comparator com)——定制排序(根据compartor接口实现的compare方法排序) */ @Test public void test2(){ emps.stream() .map(Employee::getName) .sorted() .forEach(System.out::println); System.out.println("------------------------------------"); emps.stream() .sorted((x, y) -> { if(x.getAge() == y.getAge()){ return x.getName().compareTo(y.getName()); }else{ return Integer.compare(x.getAge(), y.getAge()); } }).forEach(System.out::println); }
5.查找与匹配
实例对象
package com.atguigu.java8; public class Employee { private int id; private String name; private int age; private double salary; private Status status; public Employee() { } public Employee(String name) { this.name = name; } public Employee(String name, int age) { this.name = name; this.age = age; } public Employee(int id, String name, int age, double salary) { this.id = id; this.name = name; this.age = age; this.salary = salary; } public Employee(int id, String name, int age, double salary, Status status) { this.id = id; this.name = name; this.age = age; this.salary = salary; this.status = status; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String show() { return "测试方法引用!"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); long temp; temp = Double.doubleToLongBits(salary); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Employee other = (Employee) obj; if (age != other.age) return false; if (id != other.id) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary)) return false; return true; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status + "]"; } public enum Status { FREE, BUSY, VOCATION; } }
操作如下:
package com.atguigu.java8; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.junit.Test; import com.atguigu.java8.Employee.Status; /* * 一、 Stream 的操作步骤 * * 1. 创建 Stream * * 2. 中间操作 * * 3. 终止操作 */ public class TestStreamAPI2 { List<Employee> emps = Arrays.asList( new Employee(102, "李四", 59, 6666.66, Status.BUSY), new Employee(101, "张三", 18, 9999.99, Status.FREE), new Employee(103, "王五", 28, 3333.33, Status.VOCATION), new Employee(104, "赵六", 8, 7777.77, Status.BUSY), new Employee(104, "赵六", 8, 7777.77, Status.FREE), new Employee(104, "赵六", 8, 7777.77, Status.FREE), new Employee(105, "田七", 38, 5555.55, Status.BUSY) ); //3. 终止操作 /* allMatch——检查是否匹配所有元素 anyMatch——检查是否至少匹配一个元素 noneMatch——检查是否没有匹配的元素 findFirst——返回第一个元素 findAny——返回当前流中的任意元素 count——返回流中元素的总个数 max——返回流中最大值 min——返回流中最小值 */ @Test public void test1(){ //判断是否所有状态都是BUSY boolean bl = emps.stream() .allMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(bl); //判断集合中是否有状态为BUSY的 boolean bl1 = emps.stream() .anyMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(bl1); //检查集合中是否有没匹配的元素 boolean bl2 = emps.stream() .noneMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(bl2); } @Test public void test2(){ //查找按照工资排序后的第一个 Optional<Employee> op = emps.stream() .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())) .findFirst(); System.out.println(op.get()); System.out.println("--------------------------------"); //查找状态为空闲的任意一个 Optional<Employee> op2 = emps.parallelStream() .filter((e) -> e.getStatus().equals(Status.FREE)) .findAny(); System.out.println(op2.get()); } @Test public void test3(){ //查找集合中状态为BUSY的个数 long count = emps.stream() .filter((e) -> e.getStatus().equals(Status.FREE)) .count(); System.out.println(count); //提取所有薪水字段并排序获取最高的薪水 Optional<Double> op = emps.stream() .map(Employee::getSalary) .max(Double::compare); System.out.println(op.get()); //获取薪水最低的对象 Optional<Employee> op2 = emps.stream() .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(op2.get()); } //注意:流进行了终止操作后,不能再次使用 @Test public void test4(){ Stream<Employee> stream = emps.stream() .filter((e) -> e.getStatus().equals(Status.FREE)); long count = stream.count(); stream.map(Employee::getSalary) .max(Double::compare); } }
6.终止
终止基本
package com.atguigu.java8; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import org.junit.Test; import com.atguigu.java8.Employee.Status; /* * 一、 Stream 的操作步骤 * * 1. 创建 Stream * * 2. 中间操作 * * 3. 终止操作 */ public class TestStreamAPI2 { List<Employee> emps = Arrays.asList( new Employee(102, "李四", 59, 6666.66, Status.BUSY), new Employee(101, "张三", 18, 9999.99, Status.FREE), new Employee(103, "王五", 28, 3333.33, Status.VOCATION), new Employee(104, "赵六", 8, 7777.77, Status.BUSY), new Employee(104, "赵六", 8, 7777.77, Status.FREE), new Employee(104, "赵六", 8, 7777.77, Status.FREE), new Employee(105, "田七", 38, 5555.55, Status.BUSY) ); //3. 终止操作 /* allMatch——检查是否匹配所有元素 anyMatch——检查是否至少匹配一个元素 noneMatch——检查是否没有匹配的元素 findFirst——返回第一个元素 findAny——返回当前流中的任意元素 count——返回流中元素的总个数 max——返回流中最大值 min——返回流中最小值 */ @Test public void test1(){ //判断是否所有状态都是BUSY boolean bl = emps.stream() .allMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(bl); //判断集合中是否有状态为BUSY的 boolean bl1 = emps.stream() .anyMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(bl1); //检查集合中是否有没匹配的元素 boolean bl2 = emps.stream() .noneMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(bl2); } @Test public void test2(){ //查找按照工资排序后的第一个 Optional<Employee> op = emps.stream() .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())) .findFirst(); System.out.println(op.get()); System.out.println("--------------------------------"); //查找状态为空闲的任意一个 Optional<Employee> op2 = emps.parallelStream() .filter((e) -> e.getStatus().equals(Status.FREE)) .findAny(); System.out.println(op2.get()); } @Test public void test3(){ //查找集合中状态为BUSY的个数 long count = emps.stream() .filter((e) -> e.getStatus().equals(Status.FREE)) .count(); System.out.println(count); //提取所有薪水字段并排序获取最高的薪水 Optional<Double> op = emps.stream() .map(Employee::getSalary) .max(Double::compare); System.out.println(op.get()); //获取薪水最低的对象 Optional<Employee> op2 = emps.stream() .min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(op2.get()); } //注意:流进行了终止操作后,不能再次使用 @Test public void test4(){ Stream<Employee> stream = emps.stream() .filter((e) -> e.getStatus().equals(Status.FREE)); long count = stream.count(); stream.map(Employee::getSalary) .max(Double::compare); } }
收集和分组
package com.atguigu.java8; import java.util.Arrays; import java.util.DoubleSummaryStatistics; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import org.junit.Test; import com.atguigu.java8.Employee.Status; public class TestStreamAPI3 { List<Employee> emps = Arrays.asList( new Employee(102, "李四", 79, 6666.66, Status.BUSY), new Employee(101, "张三", 18, 9999.99, Status.FREE), new Employee(103, "王五", 28, 3333.33, Status.VOCATION), new Employee(104, "赵六", 8, 7777.77, Status.BUSY), new Employee(104, "赵六", 8, 7777.77, Status.FREE), new Employee(104, "赵六", 8, 7777.77, Status.FREE), new Employee(105, "田七", 38, 5555.55, Status.BUSY) ); //3. 终止操作 /* 归约 reduce(T identity, BinaryOperator) / reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。 */ @Test public void test1(){ List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); //将起始值赋给x,从集合中取出第一个赋给y.求和后赋给x,再从集合中取出一个赋给y以此类推 //因为有起始值,所以返会结果为sum不为null Integer sum = list.stream() .reduce(0, (x, y) -> x + y); System.out.println(sum); //求和 System.out.println("----------------------------------------"); //结果返会可能为空,所以返会结果为Optional Optional<Double> op = emps.stream() .map(Employee::getSalary) .reduce(Double::sum); System.out.println(op.get()); } //需求:搜索名字中 “六” 出现的次数 @Test public void test2(){ Optional<Integer> sum = emps.stream() .map(Employee::getName) .flatMap(TestStreamAPI1::filterCharacter) .map((ch) -> { if(ch.equals(\'六\')) return 1; else return 0; }).reduce(Integer::sum); System.out.println(sum.get()); } //collect——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法 @Test public void test3(){ //将所有的名字搜集到List中 List<String> list = emps.stream() .map(Employee::getName) .collect(Collectors.toList()); list.forEach(System.out::println); System.out.println("----------------------------------"); //将所有的名字搜集到Set中 Set<String> set = emps.stream() .map(Employee::getName) .collect(Collectors.toSet()); set.forEach(System.out::println); System.out.println("----------------------------------"); //搜集到HashSet中 HashSet<String> hs = emps.stream() .map(Employee::getName) .collect(Collectors.toCollection(HashSet::new)); hs.forEach(System.out::println); } @Test public void test4(){ //最高的工资 Optional<Double> max = emps.stream() .map(Employee::getSalary) .collect(Collectors.maxBy(Double::compare)); System.out.println(max.get()); //工资最高的employee Optional<Employee> op = emps.stream() .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); System.out.println(op.get()); Double sum = emps.stream() .collect(Collectors.summingDouble(Employee::getSalary)); System.out.println(sum); //平均值 Double avg = emps.stream() .collect(Collectors.averagingDouble(Employee::getSalary)); System.out.println(avg); //求总数 Long count = emps.stream() .collect(Collectors.counting()); System.out.println(count); System.out.println("--------------------------------------------"); //获取统计类,获取各种统计数据 DoubleSummaryStatistics dss = emps.stream() .collect(Collectors.summarizingDouble(Employee::getSalary)); System.out.println(dss.getMax()); System.out.println(dss.getAverage()); System.out.println(dss.getSum()); } //分组 @Test public void test5(){ Map<Status, List<Employee>> map = emps.stream() .collect(Collectors.groupingBy(Employee::getStatus)); System.out.println(map); } //多级分组 @Test public void test6(){ //先按照状态分组,然后按照年龄段分组 Map<Status, Map<String, List<Employee>>> map = emps.stream() .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> { if(e.getAge() >= 60) return "老年"; else if(e.getAge() >= 35) return "中年"; else return "成年"; }))); System.out.println(map); } //分区:分为true和false两个区. @Test public void test7(){ Map<Boolean, List<Employee>> map = emps.stream() .collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000)); System.out.println(map); } //连接字符串 @Test public void test8(){ String str = emps.stream() .map(Employee::getName) .collect(Collectors.joining("," , "----", "----"));//----xxxx---- System.out.println(str); } @Test public void test9(){ Optional<Double> sum = emps.stream() .map(Employee::getSalary) .collect(Collectors.reducing(Double::sum)); System.out.println(sum.get()); } }
Stream练习
实体类
package com.atguigu.exer; //交易员类 public class Trader { private String name; private String city; public Trader() { } public Trader(String name, String city) { this.name = name; this.city = city; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "Trader [name=" + name + ", city=" + city + "]"; } }
练习类
package com.atguigu.exer; import java.util.Arrays; import java.util.List; import java.util.Optional; import以上是关于jdk8-stream的api的主要内容,如果未能解决你的问题,请参考以下文章Android 插件化VirtualApp 源码分析 ( 目前的 API 现状 | 安装应用源码分析 | 安装按钮执行的操作 | 返回到 HomeActivity 执行的操作 )(代码片段
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段