java jdk1.8新特性Stream API
1、创建Streampackage com.stream.api1;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;import org.junit.Test;/*** 一 、 Stream 的三个操作步骤 1、创建Stream 2、中级操作 3、终止操作(终端操作)** @author Administrator**/public class TestStreamAPI1 { // 创建Stream @Test public void test1() { // 1、可以通过Collection 系列集合提供的stream()或parallelStream() List<String> list = new ArrayList<String>(); Stream<String> stream1 = list.stream(); // 2、通过Arrays中的静态方法stream()获取数组流 Employee[] ems = new Employee[10]; Stream<Employee> stream2 = Arrays.stream(ems); // 3、通过Stream类中的静态方法of() Stream<String> stream3 = Stream.of("aa", "bb", "cc", "dd"); // 4、创建无限流 Stream<Integer> stream4 = Stream.iterate(0, x -> x + 2); // stream4.forEach(System.out::println); stream4.limit(10).forEach(System.out::println); // 生成 Stream.generate(() -> Math.random()).limit(5).forEach(System.out::println); }}
2、Stream筛选和切片package com.stream.api2;import java.util.Arrays;import j锾攒揉敫ava.util.Iterator;import java.util.List;import java.util.stream.Stream;import org.junit.Test;import com.stream.api1.Employee;/*** 一 、 Stream 的三个操作步骤 1、创建Stream 2、中级操作 3、终止操作(终端操作)** @author Administrator**/public class TestStreamAPI2 { List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99), new Employee("小明", 15, 4500.99), new Employee("小丽", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99), new Employee("李静", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99)); // 中间操作 /** * 筛选与切片 filter —— 接收Lambda,从流中排除某些元素 limit —— 截断流,使其元素不超过给定数量。 skip(n) —— * 跳过元素,返回一个扔掉了前n个元素的流。若流中元素不足n个,则返回一个空流。与limit(n)互补 distinct —— * 筛选,通过流所生成元素的hashCode()和equals()去除重复元素 * * * 注意:使用distinct去重需要重写hashcode和equals方法 */ // 内部迭代:迭代操作有Stream API完成。 @Test public void test1() { // 中间操作:不会执行任何操作 Stream<Employee> stream1 = employees.stream().filter((e) -> { System.out.println("Stream API中间操作"); return e.getAge() > 17; }); // 终止操作:一次性执行全部内容,即“惰性求值” stream1.forEach(System.out::println); } // 外部迭代 @Test public void test2() { Iterator<Employee> it = employees.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } // 短路,limit一旦找到合适的数据将不再继续执行,一定程度上提高了性能 @Test public void test3() { employees.stream().filter((e) -> { System.out.println("短路!"); return e.getSalary() > 5000; }).limit(2).forEach(System.out::println); ; } @Test public void test4() { employees.stream().filter((e) -> e.getSalary() > 1000).skip(2).limit(2).forEach(System.out::println); ; } @Test public void test5() { employees.stream().filter((e) -> e.getSalary() > 1000).skip(2).distinct().forEach(System.out::println); ; }}
3、/3、Stream映射package com.stream.api3;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;import org.junit.Test;import com.stream.api1.Employee;public class TestStreamAPI3 { List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99), new Employee("小明", 15, 4500.99), new Employee("小丽", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99), new Employee("李静", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99)); /** * * 映射 map —— Lambda,将元素转换成其它形式或提取信息,接收一个函数作为参数,改函数会被应用到每个元素上, 并将其映射成一个新的元素。 * flatMap —— 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连城一个流。 */ @Test public void test6() { List<String> list = Arrays.asList("aaa", "bbb", "bbb", "ddd"); list.stream().map((str) -> str.toUpperCase()).forEach(System.out::println); System.out.println("---------------------------"); employees.stream().map(Employee::getName).forEach(System.out::println); System.out.println("---------------------------"); Stream<Stream<Character>> stream = list.stream().map(TestStreamAPI3::filterCharacter); stream.forEach((sm) -> { sm.forEach(System.out::println); }); System.out.println("---------------------------"); Stream<Character> stream2 = list.stream().flatMap(TestStreamAPI3::filterCharacter); stream2.forEach(System.out::println); } public static Stream<Character> filterCharacter(String str) {// add(Object obj) addAll(collection coll) List<Character> list = new ArrayList<>(); for (Character character : str.toCharArray()) { list.add(character); } return list.stream(); }}
4、Stream排序package com.stream.api4;import java.util.Arrays;import java.util.List;import org.junit.Test;import com.stream.api1.Employee;public class TestStreamAPI4 { List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99), new Employee("小明", 15, 4500.99), new Employee("小丽", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99), new Employee("李静", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99)); /** * 排序 sorted() —— 自然排序(Comparable) sorted(Comparater com) —— 定制排序(Comparater) */ @Test public void test1() { List<String> list = Arrays.asList("ccc", "aaa", "bbb", "ddd", "eee"); list.stream().sorted().forEach(System.out::println); System.out.println("--------------------------------------------"); employees.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); }}
5、Stream查找与匹配package com.stream.api5;import java.util.Arrays;import java.util.List;import java.util.Optional;import org.junit.Test;import com.stream.api1.Employee;import com.stream.api1.Employee.Status;public class TestStreamAPI5 { List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99, Status.BUSY), new Employee("小明", 15, 4500.99, Status.BUSY), new Employee("小丽", 16, 5500.99, Status.BUSY), new Employee("王二", 32, 1100.99, Status.FREE), new Employee("二虎", 22, 9825.99, Status.FREE), new Employee("李静", 18, 4502.99, Status.FREE), new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION)); /** * 查找与匹配 allMatch —— 检查是否平匹配所有元素 anyMatch —— 检查是否至少匹配一个元素 noneMatch —— * 检查是否没有匹配的元素 findFirst —— 返回第一个元素 findAny —— 返回当前流中的任意元素 count —— 返回流中元素的总个数 * max —— 返回流中最大值 min —— 返回流中最小值 */ @Test public void test1() { boolean b1 = employees.stream().allMatch(e -> e.getStatus().equals(Status.BUSY)); System.out.println(b1); boolean b2 = employees.stream().anyMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(b2); boolean b3 = employees.stream().noneMatch((e) -> e.getStatus().equals(Status.BUSY)); System.out.println(b3); Optional<Employee> op1 = employees.stream().sorted((e1, e2) -> -Double.compare(e1.getSalary(), e2.getSalary())) .findFirst(); System.out.println(op1.get()); Optional<Employee> op2 = employees.stream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny(); System.out.println(op2.get()); Optional<Employee> op3 = employees.parallelStream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny(); System.out.println(op3.get()); } @Test public void test2() { Long count = employees.stream().count(); System.out.println(count); Optional<Employee> op1 = employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())); System.out.println(op1.get()); Optional<Double> op2 = employees.stream().map(Employee::getSalary).max(Double::compare); System.out.println(op2.get()); }}
6、Stream约与收集归package com.stream.api6;import java.util.Arrays;i罪焐芡拂mport 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.stream.api1.Employee;import com.stream.api1.Employee.Status;public class TestStreamAPI6 { List<Employee> employees = Arrays.asList(new Employee("张三", 12, 1200.99, Status.BUSY), new Employee("小明", 15, 4500.99, Status.BUSY), new Employee("小丽", 16, 5500.99, Status.BUSY), new Employee("王二", 32, 1100.99, Status.FREE), new Employee("二虎", 22, 9825.99, Status.FREE), new Employee("李静", 18, 4502.99, Status.FREE), new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION)); /** * 归约 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); Integer sum = list.stream().reduce(0, (x, y) -> x + y); System.out.println(sum); System.out.println("-------------------------------------------"); Optional<Double> op1 = employees.stream().map(Employee::getSalary).reduce(Double::sum); System.out.println(op1.get()); } /** * 收集 collect —— 将流转换为其它形式,接收一个Collector接口的实现,用于给Stream中元素做汇总的方法 */ @Test public void test2() { List<String> list = employees.stream().map(Employee::getName).collect(Collectors.toList()); list.forEach(System.out::println); System.out.println("-----------------------"); Set<String> set = employees.stream().map(Employee::getName).collect(Collectors.toSet()); set.forEach(System.out::println); System.out.println("-----------------------"); HashSet<String> hashSet = employees.stream().map(Employee::getName) .collect(Collectors.toCollection(HashSet::new)); hashSet.forEach(System.out::println); } @Test public void test3() { // 总数 Long count = employees.stream().collect(Collectors.counting()); System.out.println(count); System.out.println("-----------------------"); // 平均值 Double avg = employees.stream().collect(Collectors.averagingDouble(Employee::getSalary)); System.out.println(avg); System.out.println("-----------------------"); // 总和 Double sum = employees.stream().collect(Collectors.summingDouble(Employee::getSalary)); System.out.println(sum); System.out.println("-----------------------"); // 最大值 Optional<Employee> max = employees.stream() .collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); System.out.println(max.get()); System.out.println("-----------------------"); // 最大值 Optional<Employee> min = employees.stream() .collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))); System.out.println(min.get()); } // 分组 @Test public void test4() { Map<Status, List<Employee>> map = employees.stream().collect(Collectors.groupingBy(Employee::getStatus)); System.out.println(map); } // 多级分组 @Test public void test5() { Map<Status, Map<String, List<Employee>>> map = employees.stream() .collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> { if (e.getAge() < 16) { return "青年"; } else if (e.getAge() < 18) { return "中年"; } else { return "老年"; } }))); System.out.println(map); } // 分区 @Test public void test6() { Map<Boolean, List<Employee>> map = employees.stream() .collect(Collectors.partitioningBy(e -> e.getSalary() > 5000)); System.out.println(map); } @Test public void test7() { DoubleSummaryStatistics collect = employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary)); System.out.println(collect.getAverage()); System.out.println(collect.getCount()); System.out.println(collect.getMax()); System.out.println(collect.getMin()); System.out.println(collect.getSum()); } @Test public void test8() { String str1 = employees.stream().map(Employee::getName).collect(Collectors.joining()); System.out.println(str1); System.out.println("---------------------------------"); String str2 = employees.stream().map(Employee::getName).collect(Collectors.joining(",")); System.out.println(str2); System.out.println("---------------------------------"); String str3 = employees.stream().map(Employee::getName).collect(Collectors.joining(",", "===", "===")); System.out.println(str3); }}
7、Stream约练习