Java Stream

tech2024-10-21  10

Java Stream

1 Stream 概述2 Stream 特性3 Stream 操作方式4 Stream 创建4.1 通过 java.util.Collection.stream() 方法用集合创建流4.2 通过 java.util.Arrays.stream(T[] array)方法用数组创建流4.3 通过 Stream的静态方法:of()、iterate()、generate() 5 Stream 中间操作5.1 Stream 筛选 filter5.2 Stream 映射 map/flatMap5.2.1 Stream map 取集合5.2.2 Stream map 最大值5.2.3 Stream map 最小值5.2.3 Stream map 计数5.2.4 Stream map 求和5.2.5 Stream map 平均值5.2.6 Stream floatMap 5.3 Stream 去重 distinct5.3.1 去重的对象重写了hashcode和equals5.3.2 去重的对象没有重写了hashcode和equals 按字段去重 5.4 Stream 排序 sorted5.4.1 Stream sorted 正序5.4.2 Stream sorted 逆序5.4.3 Stream sorted 多条件排序 5.5 Stream 收集 collect5.6 Stream 分组(partitioningBy/groupingBy)5.7 Stream limit/skip 6 Stream 终止操作(终端操作)6.1 Stream 遍历 forEach6.2 Stream 规约 reduce6.3 Stream 匹配 find/match6.4 Stream 聚合 max/min/count 7 Stream 常用函数式接口7.1 Java Stream Predicate7.2 Java Stream Consumer7.3 Java Stream Function7.4 Java Stream Supplier7.5 Java Stream UnaryOperator7.6 Java Stream BinaryOperator 8 Java 8 Builder 模式

1 Stream 概述

Stream 是用函数式编程方式在集合类上进行复杂操作的工具,其集成了Java 8中的众多新特性之一的聚合操作,开发者可以更容易地使用Lambda表达式,并且更方便地实现对集合的查找、遍历、过滤以及常见计算等。

2 Stream 特性

序号概述1Stream 只负责对数据进行处理、加工,本身不负责存储数据,存储数据是用集合,数组等数据结构。2Stream 是不可变,一旦修改,就会产生新的Stream对象。Stream不会修改数据源的数据。3Stream 的操作是一个延迟操作。所有的操作都必须延迟到终结操作时,一起处理(不到最后一步不处理)。

3 Stream 操作方式

操作方式概述中间操作每次转换原有 Stream 对象不改变,返回一个新的 Stream 对象(可以有多次转换),这就允许对其操作可以像链条一样排列,变成一个管道。终止操作(终端操作)每个流只能进行一次终端操作,终端操作结束后流无法再次使用。

4 Stream 创建

方式创建方式概述顺序流*.stream()单线程 由主线程按顺序对流执行操作并行流*.parallelStream() *.stream().parallel()多线程 内部以多线程并行执行的方式对流进行操作

4.1 通过 java.util.Collection.stream() 方法用集合创建流

List<String> list = Arrays.asList("1", "2", "3"); // 1 顺序流 用集合创建一个顺序流 Stream<String> stream = list.stream(); // 2 并行流 用集合创建一个并行流 Stream<String> parallelStream1 = list.parallelStream(); // 3 并行流 用集合创建一个顺序流然后转并行流 Stream<String> parallelStream2 = list.stream().parallel();

4.2 通过 java.util.Arrays.stream(T[] array)方法用数组创建流

int[] array = {1, 3, 4, 5, 6}; IntStream stream = Arrays.stream(array);

4.3 通过 Stream的静态方法:of()、iterate()、generate()

Stream<Integer> stream1 = Stream.of(1, 2, 3, 4, 5, 6); Stream<Integer> stream2 = Stream.iterate(0, (x) -> x + 3).limit(4); stream2.forEach(e -> System.out.print(e + "\t")); // 0 3 6 9 Stream<Double> stream3 = Stream.generate(Math::random).limit(3); stream3.forEach(e -> System.out.print(e + "\t"));

5 Stream 中间操作

5.1 Stream 筛选 filter

package com.xu.learn.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("王七", 21, "E@outlook.com"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); list.stream().filter(e -> e.getAge() > 18 && e.getAge() < 21).collect(Collectors.toList()).forEach(System.out::println); } } list.stream().filter(e -> e.getAge() > 18 && e.getAge() < 21).collect(Collectors.toList()).forEach(System.out::println); User{name='王五', age=19, email='C@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'}

5.2 Stream 映射 map/flatMap

方法解释map接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。flatMap接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。 package com.xu.learn.stream; import java.util.Arrays; import java.util.List; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("王七", 21, "E@outlook.com"); User user6 = new User("王七", 21, "E@outlook.com"); List<User> list = Arrays.asList(user6, user5, user3, user2, user1, user4); list.stream().map(e -> { if (e.getName().equals("张三")) { e.setAge(e.getAge() + 10); } return e; }).forEach(System.out::println); } } list.stream().map(e -> { if (e.getName().equals("张三")) { e.setAge(e.getAge() + 10); } return e; }).forEach(System.out::println);

5.2.1 Stream map 取集合

list.stream().map(User::getAge).forEach(System.out::println); 20 21 22

5.2.2 Stream map 最大值

package com.xu.learn.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("叶良辰", 21, "E@outlook.com"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); List<String> test = list.stream().map(User::getName).collect(Collectors.toList()); // 1 取最长的名字 Optional<String> max1 = test.stream().max(Comparator.comparing(String::length)); System.out.println("最长的名字:" + max1.get()); // 2 取最大的年纪 自然排序 int max2 = list.stream().map(User::getAge).max(Integer::compareTo).get(); System.out.println(max2); // 3 取最大的年纪 自定义排序 Optional<Integer> max3 = list.stream().map(User::getAge).max(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); max3.ifPresent(System.out::println); // 4 取最大的年纪 int max4 = list.stream().map(User::getAge).max(Integer::compareTo).get(); System.out.println(max4); // 5 取最大的年纪User对象 Optional<User> max5 = list.stream().max(Comparator.comparingInt(User::getAge)); System.out.println("最大的年纪:" + max5.get().getAge()); } } 最长的名字:叶良辰 21 21 21 最大的年纪:21

5.2.3 Stream map 最小值

int a = list.stream().map(User::getAge).min(Integer::compareTo).get(); System.out.println(a); 20

5.2.3 Stream map 计数

int a = list.stream().map(User::getAge).count(); System.out.println(a); 3

5.2.4 Stream map 求和

int a = list.stream().map(User::getAge).sum(); System.out.println(a); 63

5.2.5 Stream map 平均值

int a = list.stream().mapToInt(User::getAge).average(); System.out.println(a); 21

5.2.6 Stream floatMap

package com.xu.learn.stream; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("叶良辰", 21, "E@outlook.com"); //List<User> list1 = Arrays.asList(user5, user3, user2, user1, user4); List<User> list1 = Arrays.asList(user1, user2, user3); List<User> list2 = Arrays.asList(user3, user4, user5); // 1 交集 List<User> users1 = list1.stream().filter(list2::contains).collect(toList()); users1.stream().forEach(System.out::println); // 2 并集 List<User> users2 = Stream.of(list1, list2).flatMap(Collection::stream).distinct().collect(Collectors.toList()); users2.stream().forEach(System.out::println); // 3 差集 List<User> users3 = list1.stream().filter(e -> !list2.contains(e)).collect(toList()); users3.stream().forEach(System.out::println); // 4 合并多个 List (并集 不去重) Map<Integer, List<User>> map = new HashMap<>(); map.put(1, list1); map.put(2, list2); List<User> users4 = map.values().stream().flatMap(e -> e.stream()).collect(Collectors.toList()); users4.stream().forEach(System.out::println); } }

5.3 Stream 去重 distinct

5.3.1 去重的对象重写了hashcode和equals

package com.xu.learn.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("王七", 21, "E@outlook.com"); User user6 = new User("王七", 21, "E@outlook.com"); List<User> list = Arrays.asList(user6, user5, user3, user2, user1, user4); list.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getName)).distinct().collect(Collectors.toList()).forEach(System.out::println); } } list.stream().distinct().collect(Collectors.toList()).forEach(System.out::println); User{name='张三', age=17, email='A@outlook.com'} User{name='李四', age=18, email='B@outlook.com'} User{name='王五', age=19, email='C@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'} User{name='王七', age=21, email='E@outlook.com'}

5.3.2 去重的对象没有重写了hashcode和equals 按字段去重

package com.xu.test; import java.util.*; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Test.java * @Package com.xu.test * @Description: * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Main { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("王七", 21, "E@outlook.com"); User user6 = new User("王七", 21, "E@outlook.com"); List<User> list = Arrays.asList(user6, user5, user3, user2, user1, user4); list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(f -> f.getName() + f.getEmail()))), ArrayList::new)).forEach(System.out::println); } } list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(f -> f.getName() + f.getEmail()))), ArrayList::new)).forEach(System.out::println); User{name='张三', age=17, email='A@outlook.com'} User{name='李四', age=18, email='B@outlook.com'} User{name='王七', age=21, email='E@outlook.com'} User{name='王五', age=19, email='C@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'}

5.4 Stream 排序 sorted

package com.xu.learn.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("王七", 21, "E@outlook.com"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); list.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getName)).collect(Collectors.toList()).forEach(System.out::println); } } list.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getName)).collect(Collectors.toList()).forEach(System.out::println); User{name='王七', age=21, email='E@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'} User{name='王五', age=19, email='C@outlook.com'} User{name='李四', age=18, email='B@outlook.com'} User{name='张三', age=17, email='A@outlook.com'}

5.4.1 Stream sorted 正序

list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList()).forEach(System.out::println); User{name='张三', age=17, email='A@outlook.com'} User{name='李四', age=18, email='B@outlook.com'} User{name='王五', age=19, email='C@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'} User{name='王七', age=21, email='E@outlook.com'}

5.4.2 Stream sorted 逆序

list.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getName)).collect(Collectors.toList()).forEach(System.out::println); User{name='王七', age=21, email='E@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'} User{name='王五', age=19, email='C@outlook.com'} User{name='李四', age=18, email='B@outlook.com'} User{name='张三', age=17, email='A@outlook.com'}

5.4.3 Stream sorted 多条件排序

list.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getName)).collect(Collectors.toList()).forEach(System.out::println); User{name='王七', age=21, email='E@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'} User{name='王五', age=19, email='C@outlook.com'} User{name='李四', age=18, email='B@outlook.com'} User{name='张三', age=17, email='A@outlook.com'}

5.5 Stream 收集 collect

作用Collectors 静态方法转 ListCollectors.toList()转 SetCollectors.toSet转 MapCollectors.toMap转 StringCollectors.joining() package com.xu.learn.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("王七", 21, "E@outlook.com"); // 1 转字符串 list.stream().map(User::getName).collect(Collectors.joining(",")); // 2 转List<String> list.stream().map(User::getName).collect(Collectors.toList()); // 3 转Map<String, User> list.stream().collect(Collectors.toMap(User::getName, user -> user, (key1, key2) -> key2)); // 4 转Set<String> list.stream().map(User::getName).collect(Collectors.toSet()); } } 作用Collectors 静态方法计数Collectors.counting()平均值Collectors.averagingInt()、Collectors.averagingLong()、Collectors.averagingDouble()最值Collectors.maxB()y、Collectors.minBy()求和Collectors.summingInt()、Collectors.summingLong()、Collectors.summingDouble()统计以上所有Collectors.summarizingInt()、Collectors.summarizingLong()、Collectors.summarizingDouble() package com.xu.learn.stream; import java.util.Arrays; import java.util.DoubleSummaryStatistics; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("叶良辰", 21, "E@outlook.com"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); List<Integer> integers = list.stream().map(User::getAge).collect(toList()); // 1 计数 Long count = list.stream().collect(Collectors.counting()); System.out.println(count); // 2 求平均值 Double average = list.stream().collect(Collectors.averagingDouble(User::getAge)); System.out.println(average); // 3 求最大值 Optional<Integer> max = list.stream().map(User::getAge).collect(Collectors.maxBy(Integer::compare)); System.out.println(max.get()); // 4 求和 Integer sum = list.stream().collect(Collectors.summingInt(User::getAge)); System.out.println(sum); // 一次性统计所有信息 DoubleSummaryStatistics collect = list.stream().collect(Collectors.summarizingDouble(User::getAge)); System.out.println(collect); } }

5.6 Stream 分组(partitioningBy/groupingBy)

package com.xu.learn.stream; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com", "男"); User user2 = new User("李四", 18, "C@outlook.com", "男"); User user3 = new User("王五", 19, "C@outlook.com", "男"); User user4 = new User("东方不败", 20, "C@outlook.com", "女"); User user5 = new User("叶良辰", 21, "E@outlook.com", "女"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); List<Integer> integers = list.stream().map(User::getAge).collect(toList()); // 1 将年龄大于 19 的分组 Map<Boolean, List<User>> part = list.stream().collect(Collectors.partitioningBy(x -> x.getAge() > 19)); System.out.println(part); // 2 按性别分组 Map<String, List<User>> group1 = list.stream().collect(Collectors.groupingBy(User::getSex)); System.out.println(group1); // 3 先按性别分组 再按邮箱分组 Map<String, Map<String, List<User>>> group2 = list.stream().collect(Collectors.groupingBy(User::getSex, Collectors.groupingBy(User::getEmail))); System.out.println(group2); } } {false=[User{name='王五', email='C@outlook.com', age=19, sex='男'}, User{name='李四', email='C@outlook.com', age=18, sex='男'}, User{name='张三', email='A@outlook.com', age=17, sex='男'}], true=[User{name='叶良辰', email='E@outlook.com', age=21, sex='女'}, User{name='东方不败', email='C@outlook.com', age=20, sex='女'}]} {=[User{name='叶良辰', email='E@outlook.com', age=21, sex='女'}, User{name='东方不败', email='C@outlook.com', age=20, sex='女'}],=[User{name='王五', email='C@outlook.com', age=19, sex='男'}, User{name='李四', email='C@outlook.com', age=18, sex='男'}, User{name='张三', email='A@outlook.com', age=17, sex='男'}]} {={C@outlook.com=[User{name='东方不败', email='C@outlook.com', age=20, sex='女'}], E@outlook.com=[User{name='叶良辰', email='E@outlook.com', age=21, sex='女'}]},={A@outlook.com=[User{name='张三', email='A@outlook.com', age=17, sex='男'}], C@outlook.com=[User{name='王五', email='C@outlook.com', age=19, sex='男'}, User{name='李四', email='C@outlook.com', age=18, sex='男'}]}}

5.7 Stream limit/skip

package com.xu.learn.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com", "男"); User user2 = new User("李四", 18, "C@outlook.com", "男"); User user3 = new User("王五", 19, "C@outlook.com", "男"); User user4 = new User("东方不败", 20, "C@outlook.com", "女"); User user5 = new User("叶良辰", 21, "E@outlook.com", "女"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); list.stream().skip(1).limit(2).collect(Collectors.toList()).forEach(System.out::println); } } User{name='王五', email='C@outlook.com', age=19, sex='男'} User{name='李四', email='C@outlook.com', age=18, sex='男'}

6 Stream 终止操作(终端操作)

6.1 Stream 遍历 forEach

package com.xu.learn.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("王七", 21, "E@outlook.com"); User user6 = new User("王七", 21, "E@outlook.com"); List<User> list = Arrays.asList(user6, user5, user3, user2, user1, user4); list.stream().filter(e -> e.getAge() > 18 && e.getAge() < 21).collect(Collectors.toList()).forEach(System.out::println); list.stream().filter(e -> e.getAge() > 18 && e.getAge() < 21).collect(Collectors.toList()).forEach(user -> System.out.println(user.toString())); } } list.forEach(e -> System.out.println(e.toString())); list.stream().forEach(e -> System.out.println(e.toString())); list.stream().forEach(System.out::println); User{name='张三', age=17, email='A@outlook.com'} User{name='李四', age=18, email='B@outlook.com'} User{name='王五', age=19, email='C@outlook.com'} User{name='赵六', age=20, email='D@outlook.com'} User{name='王七', age=21, email='E@outlook.com'}

6.2 Stream 规约 reduce

package com.xu.learn.stream; import java.util.Arrays; import java.util.List; import java.util.Optional; import static java.util.stream.Collectors.toList; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com"); User user2 = new User("李四", 18, "B@outlook.com"); User user3 = new User("王五", 19, "C@outlook.com"); User user4 = new User("赵六", 20, "D@outlook.com"); User user5 = new User("叶良辰", 21, "E@outlook.com"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); List<Integer> integers = list.stream().map(User::getAge).collect(toList()); // 1 求和 Optional<Integer> sum1 = integers.stream().reduce((x, y) -> x + y); System.out.println(sum1.get()); // 2 求和 Optional<Integer> sum2 = integers.stream().reduce(Integer::sum); sum2.ifPresentOrElse(e -> { System.out.println(e); }, () -> { System.out.println("0"); }); // 3 求和 Integer sum3 = integers.stream().reduce(0, Integer::sum); sum2.ifPresent(System.out::println); // 4 求乘积 Optional<Integer> product = integers.stream().reduce((x, y) -> x * y); product.ifPresent(System.out::println); // 5 求最大值 Optional<Integer> max1 = integers.stream().reduce((x, y) -> x > y ? x : y); max1.ifPresent(System.out::println); // 6 求最大值 Integer max2 = integers.stream().reduce(1, Integer::max); System.out.println(max2); } } 95 95 95 2441880 21 21

6.3 Stream 匹配 find/match

package com.xu.learn.stream; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com", "男"); User user2 = new User("李四", 18, "C@outlook.com", "男"); User user3 = new User("王五", 19, "C@outlook.com", "男"); User user4 = new User("东方不败", 20, "C@outlook.com", "女"); User user5 = new User("叶良辰", 21, "E@outlook.com", "女"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); Optional<User> findFirst = list.stream().filter(e -> e.getSex().equals("男")).findFirst(); findFirst.ifPresent(System.out::println); Optional<User> findAny = list.stream().filter(e -> e.getSex().equals("男")).findAny(); findAny.ifPresentOrElse(System.out::println, () -> { System.out.println("无性别为男的数据"); }); boolean allMatch = list.stream().allMatch(e -> e.getSex().equals("男")); System.out.println("是全部性别为男的数据:" + allMatch); boolean anyMatch = list.stream().anyMatch(e -> e.getSex().equals("男")); System.out.println("是否有性别为男的数据:" + anyMatch); } } User{name='王五', email='C@outlook.com', age=19, sex='男'} User{name='王五', email='C@outlook.com', age=19, sex='男'} 是全部性别为男的数据:false 是否有性别为男的数据:true

6.4 Stream 聚合 max/min/count

package com.xu.learn.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * All rights Reserved, Designed By Hyacinth * * @version V1.0 * @Title: Learn.java * @Package com.xu.learn.stream * @Description: Java 8 Stream * @author: hyacinth * @date: 2020年9月3日 下午8:18:23 * @Copyright: */ public class Learn { public static void main(String[] args) { User user1 = new User("张三", 17, "A@outlook.com", "男"); User user2 = new User("李四", 18, "C@outlook.com", "男"); User user3 = new User("王五", 19, "C@outlook.com", "男"); User user4 = new User("东方不败", 20, "C@outlook.com", "女"); User user5 = new User("叶良辰", 21, "E@outlook.com", "女"); List<User> list = Arrays.asList(user5, user3, user2, user1, user4); List<String> test = list.stream().map(User::getName).collect(Collectors.toList()); // 1 取最长的名字 Optional<String> max1 = test.stream().max(Comparator.comparing(String::length)); System.out.println("最长的名字:" + max1.get()); // 2 取最大的年纪 自然排序 int max2 = list.stream().map(User::getAge).max(Integer::compareTo).get(); System.out.println(max2); // 3 取最大的年纪 自定义排序 Optional<Integer> max3 = list.stream().map(User::getAge).max(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); max3.ifPresent(System.out::println); // 4 取最大的年纪 int max4 = list.stream().map(User::getAge).max(Integer::compareTo).get(); System.out.println(max4); // 5 取最大的年纪User对象 Optional<User> max5 = list.stream().max(Comparator.comparingInt(User::getAge)); System.out.println("最大的年纪:" + max5.get().getAge()); List<Integer> integers = list.stream().map(User::getAge).collect(Collectors.toList()); // 6 计数 Long count = list.stream().collect(Collectors.counting()); System.out.println(count); // 7 最小值 int a = list.stream().map(User::getAge).min(Integer::compareTo).get(); System.out.println(a); } } 最长的名字:东方不败 21 21 21 最大的年纪:21 5 17

7 Stream 常用函数式接口

函数式接口定义作用Functio<T, R>方法Fcuntion 接口是对接受一个 T 类型参数,返回R类型的结果的方法的抽象,通过调用apply方法执行内容。Consumer<T>消费者该接口对应的方法类型为接收一个参数,没有返回值。Supplier<T>生产者该接口不接受参数,但是提供一个返回值。Predicate<T>判断该接口对应的方法为接收一个参数,返回一个Boolean类型值,多用于判断与过滤。

7.1 Java Stream Predicate

函数接口抽象方法功能Predicate<T>test(T t)判断真假Predicate<T>and(Predicate<? super T> other)并且Predicate<T>or(Predicate<? super T> other)或者Predicate<T>negate()取反 package com.xu.music; import java.util.function.Predicate; public class Test { public static void main(String[] args) { Predicate<Integer> predicate = age -> age > 24; Student student = new Student(175, 23, "张三"); System.out.println("张三大于24岁吗?" + predicate.test(student.getAge())); } } 张三大于24岁吗?false package com.xu.music; import java.util.function.Predicate; public class Test { public static void main(String[] args) { System.out.println(and((s) -> s.length() > 5,(s1) -> s1.contains("H"),"Hello")); System.out.println(or((s) -> s.length() > 20,(s1) -> s1.contains("H"),"Hello")); } public static Boolean and(Predicate<String> str1,Predicate<String> str2,String str) { return str1.and(str2).test(str); } public static Boolean or(Predicate<String> str1,Predicate<String> str2,String str) { return str1.or(str2).test(str); } public static Boolean negate(Predicate<String> str1,Predicate<String> str2,String str) { return str1.or(str2).negate().test(str); } } false true

7.2 Java Stream Consumer

函数接口抽象方法功能Consumer<T>accept(T t)消费消息 package com.xu.music; import java.util.function.Consumer; public class Test { public static void main(String[] args) { Consumer<String> consumer = System.out::println; consumer.accept("随便输出一些东西"); } } 随便输出一些东西

7.3 Java Stream Function

函数接口抽象方法功能Function<T, R>apply(T t)T映射为R package com.xu.music; import java.util.function.Function; public class Test { public static void main(String[] args) { Function<Student, String> function = Student::getName; Student student = new Student(175, 23, "张三"); String name = function.apply(student); System.out.println("-->" + name); } } -->张三

7.4 Java Stream Supplier

函数接口抽象方法功能Supplier<T>get()生产消息 package com.xu.music; import java.util.function.Function; import java.util.function.Supplier; public class Test { public static void main(String[] args) { Student student = new Student(175, 23, "张三"); Function<Student, Integer> function = Student::getAge; Supplier<Integer> supplier = () -> Integer.valueOf(function.apply(student)); System.out.println(supplier.get()); } } 23

7.5 Java Stream UnaryOperator

函数接口抽象方法功能UnaryOperatorapply(T t)一元操作 package com.xu.music; import java.util.function.Predicate; import java.util.function.UnaryOperator; public class Test { public static void main(String[] args) { Student student = new Student(175, 23, "张三"); Predicate<Integer> predicate = age -> age > 24; UnaryOperator<Boolean> unaryOperator = uglily -> predicate.test(student.getAge()); Boolean apply = unaryOperator.apply(true); System.out.println(apply); } } false

7.6 Java Stream BinaryOperator

函数接口抽象方法功能BinaryOperatorapply(T t, U u)二元操作 package com.xu.music; import java.util.function.BinaryOperator; public class Test { public static void main(String[] args) { BinaryOperator<Integer> operator = (x, y) -> x * y; Integer integer = operator.apply(2, 3); System.out.println(integer); } } 6

8 Java 8 Builder 模式

package com.xu.builder; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; public class Builder<T> { private final Supplier<T> supplier; private List<Consumer<T>> list = new ArrayList<>(); public Builder(Supplier<T> supplier) { this.supplier = supplier; } public static <T> Builder<T> of(Supplier<T> supplier) { return new Builder<T>(supplier); } public <V> Builder<T> width(Consumer1<T, V> consumer1, V v) { list.add(e -> consumer1.accept(e, v)); return this; } public T build() { T t = supplier.get(); list.stream().forEach(e -> e.accept(t)); return t; } @FunctionalInterface public interface Consumer1<T, V> { void accept(T t, V v); } } package com.xu.builder; public class Test { public static void main(String[] args) { Student student = Builder.of(Student::new) .width(Student::setName,"1111") .width(Student::setAge,11).build(); System.out.println(student.toString()); } } "C:\Program Files\Java\jdk-11.0.8\bin\java.exe" "-javaagent:D:\IDE\IntelliJ IDEA 2020.3.1\lib\idea_rt.jar=7449:D:\IDE\IntelliJ IDEA 2020.3.1\bin" -Dfile.encoding=UTF-8 -classpath E:\SourceCode\Idea-2020.2\OpenCV\out\production\OpenCV com.xu.builder.Test Student{name='1111', age=11} Process finished with exit code 0
最新回复(0)