* Stream 的三个操作步骤:
* 1创建Stream
* 2中间操作
* 3终止操作
package airycode_java8.nice6; import airycode_java8.nice1.Employee; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * Stream 的三个操作步骤: * 1创建Stream * 2中间操作 * 3终止操作 * Created by admin on 2019/1/3. */ public class TestStream { @Test public void test1(){ //1.通过Collection集合提供的stream()或者parallelStream() List<String> list = new ArrayList<>(); Stream<String> stream1 = list.stream(); //2.数组 Employee[]emps = new Employee[10]; Stream<Employee> stream2 = Arrays.stream(emps); //3.stream中的静态方法 Stream.of("aa","bb","cc"); //4.创建无限流 //迭代 Stream<Integer> stream = Stream.iterate(0, (x) -> x + 2); stream.limit(10).forEach(System.out::println); //生成 Stream.generate(()->Math.random()).limit(5).forEach(System.out::println); } }
中间操作:
package airycode_java8.nice6; import airycode_java8.nice1.Employee; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * 中间操作 * * Created by admin on 2019/1/3. */ public class TestStreamApi2 { //准备数据 static List<Employee> employeeList = Arrays.asList( new Employee("张三",18,9999.99, Employee.Status.FREE), new Employee("李四",38,5555.55,Employee.Status.BUSY), new Employee("王五",50,6666.66,Employee.Status.VOCATION), new Employee("赵六",16,3333.33,Employee.Status.FREE), new Employee("田七",8,7777.77,Employee.Status.BUSY) ); /*** * 筛选与切片 * filter--接收Lambda,从流中排除某些元素。 * limit--截断流,使其元素不超过给定数量 * skip(n)--跳过元素,返回扔掉了前n个元素的流,若流中不足n个,则返回一个空流,与limit互补 * distinct--筛选,通过流所生成的元素的hashcode和equals去除重复元素 */ //内部迭代:由StreamAPI提供 @Test public void test1(){ //中间操作:不会做任何的操作 Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35); //终止操作:一次性执行全部,就是“惰性求值” stream1.forEach(System.out::println); } @Test public void test2(){ //中间操作:不会做任何的操作 Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35).limit(1); //终止操作:一次性执行全部,就是“惰性求值” stream1.forEach(System.out::println); } @Test public void test3(){ //中间操作:不会做任何的操作 Stream<Employee> stream1 = employeeList.stream().filter((e) -> e.getAge() > 35).skip(1); //终止操作:一次性执行全部,就是“惰性求值” stream1.forEach(System.out::println); } //去重必须重写hashcode和equals @Test public void test4(){ //中间操作:不会做任何的操作 Stream<Employee> stream1 = employeeList.stream().filter((e) ->e.getSalary()>5000).skip(2).distinct(); //终止操作:一次性执行全部,就是“惰性求值” stream1.forEach(System.out::println); } }
中间操作2:
package airycode_java8.nice6; import airycode_java8.nice1.Employee; import org.junit.Test; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * 中间操作 * * Created by admin on 2019/1/3. */ public class TestStreamApi3 { //准备数据 static List<Employee> employeeList = Arrays.asList( new Employee("张三",18,9999.99, Employee.Status.FREE), new Employee("李四",38,5555.55,Employee.Status.BUSY), new Employee("王五",50,6666.66,Employee.Status.VOCATION), new Employee("赵六",16,3333.33,Employee.Status.FREE), new Employee("田七",8,7777.77,Employee.Status.BUSY) ); /*** * 映射 * map--接收Lambda,将元素转换成其他形式或提取信息,接收一个函数作为参数,该函数会被应用到每一个元素上,并将其映射成一个新的元素 * flatMap--接收一个函数作为参数,将流中的,每一个值换成另一个流,然后把所有流链接成一个流 */ //内部迭代:由StreamAPI提供 @Test public void test1(){ List<String> list = Arrays.asList("aaa","bbb","ccc","ddd"); list.stream().map((str)->str.toUpperCase()).forEach(System.out::println); System.out.println("------------------------"); employeeList.stream().map((employee -> employee.getName())).forEach(System.out::println); } //map对比flatMap @Test public void test2(){ List<String> list = Arrays.asList("aaa","bbb","ccc","ddd"); Stream<Stream<Character>> charStream = list.stream().map(TestStreamApi3::filterChar); charStream.forEach((sm)->{ sm.forEach(System.out::println); }); } //flatMap @Test public void test3(){ List<String> list = Arrays.asList("aaa","bbb","ccc","ddd"); list.stream().flatMap(TestStreamApi3::filterChar).forEach(System.out::println); } public static Stream<Character> filterChar(String str){ List<Character> list = new ArrayList<>(); for (Character c:str.toCharArray()) { list.add(c); } return list.stream(); } }
中间操作-排序
package airycode_java8.nice6; import airycode_java8.nice1.Employee; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * 中间操作--排序 * * Created by admin on 2019/1/3. */ public class TestStreamApi4 { //准备数据 static List<Employee> employeeList = Arrays.asList( new Employee("张三",18,9999.99, Employee.Status.FREE), new Employee("李四",38,5555.55,Employee.Status.BUSY), new Employee("王五",50,6666.66,Employee.Status.VOCATION), new Employee("赵六",16,3333.33,Employee.Status.FREE), new Employee("田七",8,7777.77,Employee.Status.BUSY) ); /*** * 排序 * sorted()-自然排序 * sorted(Comparator com)--定制排序 */ @Test public void test1(){ List<String> list = Arrays.asList("fff","aaa","bbb","ccc","ddd"); list.stream().sorted().forEach(System.out::println); System.out.println("---------------------"); employeeList.stream().sorted((e1,e2)->{ if (e1.getAge() == e2.getAge()) { return e1.getName().compareTo(e2.getName()); } else { return -Integer.compare(e1.getAge(),e2.getAge()); } }).forEach(System.out::println); } }
终止操作:
package airycode_java8.nice6; import airycode_java8.nice1.Employee; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * 终止操作 * * Created by admin on 2019/1/3. */ public class TestStreamApi5 { //准备数据 static List<Employee> employeeList = Arrays.asList( new Employee("张三",18,9999.99, Employee.Status.FREE), new Employee("李四",38,5555.55,Employee.Status.BUSY), new Employee("王五",50,6666.66,Employee.Status.VOCATION), new Employee("赵六",16,3333.33,Employee.Status.FREE), new Employee("田七",8,7777.77,Employee.Status.BUSY) ); /*** * 终止操作 * 查找与匹配 * allMatch--检查是否匹配所有元素 * anyMatch--检查是否至少匹配一个元素 * noneMatch--检查是否没有匹配所有元素 * findFirst--返回第一个元素 * findAny--返回当前流中的任意一个元素 * count--返回流中元素总个数 * max--返回流中最大值 * min--返回流中最小值 * * */ @Test public void test1(){ boolean allMatch = employeeList.stream().allMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY))); System.out.println(allMatch); boolean anyMatch = employeeList.stream().anyMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY))); System.out.println(anyMatch); boolean noneMatch = employeeList.stream().noneMatch((employee -> employee.getStatus().equals(Employee.Status.BUSY))); System.out.println(noneMatch); Optional<Employee> op = employeeList.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())).findFirst(); Employee employee = op.get(); System.out.println(employee); System.out.println("-------------------------"); Optional<Employee> anyOp = employeeList.stream().filter((e) -> e.getStatus().equals(Employee.Status.FREE)).findAny(); System.out.println(anyOp.get()); } @Test public void test2(){ long count = employeeList.stream().count(); System.out.println(count); Optional<Employee> max = employeeList.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(max.get()); Optional<Employee> min = employeeList.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(min.get()); Optional<Double> min1 = employeeList.stream().map(Employee::getSalary).min(Double::compare); System.out.println(min1.get()); } }
终止操作:规约
package airycode_java8.nice6; import airycode_java8.nice1.Employee; import org.junit.Test; import java.util.*; import java.util.stream.Collectors; /** * 终止操作 * * Created by admin on 2019/1/3. */ public class TestStreamApi6 { //准备数据 static List<Employee> employeeList = Arrays.asList( new Employee("张三",18,9999.99, Employee.Status.FREE), new Employee("李四",38,5555.55,Employee.Status.BUSY), new Employee("王五",50,6666.66,Employee.Status.VOCATION), new Employee("赵六",16,3333.33,Employee.Status.FREE), new Employee("田七",8,7777.77,Employee.Status.BUSY) ); /*** * 规约 * reduce(T identity,BinaryOperator)--可以将流中元素反复结合起来,得到一个值 * * */ @Test public void test1(){ List<Integer> list = Arrays.asList(1,2,3,4,5); Integer sum = list.stream().reduce(0, (x, y) -> x + y); System.out.println(sum); System.out.println("-----------------------"); Optional<Double> reduceOp = employeeList.stream().map(Employee::getSalary).reduce(Double::sum); System.out.println(reduceOp.get()); } /*** * 收集 * collect--将流转化为其他的形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法 */ @Test public void test2(){ List<String> names = employeeList.stream().map(Employee::getName).collect(Collectors.toList()); names.forEach(System.out::println); Set<String> disNames = employeeList.stream().map(Employee::getName).collect(Collectors.toSet()); disNames.forEach(System.out::println); System.out.println("----------------"); HashSet<String> hashNames = employeeList.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new)); hashNames.forEach(System.out::println); } @Test public void test3(){ //总数 Long count = employeeList.stream().collect(Collectors.counting()); System.out.println(count); //平均数 Double avg = employeeList.stream().collect(Collectors.averagingDouble(Employee::getSalary)); System.out.println(avg); //总和 Double sum = employeeList.stream().collect(Collectors.summingDouble(Employee::getSalary)); System.out.println(sum); //最大值员工 Optional<Employee> employeeMax = employeeList.stream().collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); System.out.println(employeeMax.get()); //最小值 Optional<Double> val = employeeList.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare)); System.out.println(val.get()); } //分组 @Test public void test4(){ Map<Employee.Status, List<Employee>> statusListMap = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus)); System.out.println(statusListMap); } //多级分组 @Test public void test5(){ Map<Employee.Status, Map<String, List<Employee>>> map = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((employee) -> { if (employee.getAge() <= 35) { return "青年"; } else if (employee.getAge() <= 50) { return "中年"; } else { return "老年"; } }))); System.out.println(map); } //分区 @Test public void test6(){ Map<Boolean, List<Employee>> booleanListMap = employeeList.stream().collect(Collectors.partitioningBy((e) -> e.getSalary() > 8000)); System.out.println(booleanListMap); } //获取最大值,求和,最小值,另一种方式 @Test public void test7(){ DoubleSummaryStatistics dss = employeeList.stream().collect(Collectors.summarizingDouble(Employee::getSalary)); System.out.println(dss.getSum()); System.out.println(dss.getAverage()); System.out.println(dss.getCount()); System.out.println(dss.getMax()); System.out.println(dss.getMin()); } //连接字符换 @Test public void test8(){ String str = employeeList.stream().map(Employee::getName).collect(Collectors.joining("-")); System.out.println(str); } }