Java8中stream流处理数据21个小案例(学习使用)

简介: Java8中stream流处理数据21个小案例(学习使用)

1、首先准备两个类(苹果类,可以一个苹果颜色的枚举)

1. public class Apple {
2. // 名字
3. private String name;
4. // 重量
5. private double weight;
6. // 颜色(枚举类)
7. private Color color;
8. // 城市
9. private String nation;
10. 
11. public Apple() {
12.     }
13. 
14. @Override
15. public String toString() {
16. return "Apple{" +
17. "name='" + name + '\'' +
18. ", weight=" + weight +
19. ", color=" + color +
20. ", nation='" + nation + '\'' +
21. '}';
22.     }
23. 
24. @Override
25. public int hashCode() {
26. return Objects.hash(name, weight, color, nation);
27.     }
28. 
29. public String getName() {
30. return name;
31.     }
32. 
33. public void setName(String name) {
34. this.name = name;
35.     }
36. 
37. public double getWeight() {
38. return weight;
39.     }
40. 
41. public void setWeight(double weight) {
42. this.weight = weight;
43.     }
44. 
45. public Color getColor() {
46. return color;
47.     }
48. 
49. public void setColor(Color color) {
50. this.color = color;
51.     }
52. 
53. public String getNation() {
54. return nation;
55.     }
56. 
57. public void setNation(String nation) {
58. this.nation = nation;
59.     }
60. 
61. public Apple(String name, double weight, Color color, String nation) {
62. this.name = name;
63. this.weight = weight;
64. this.color = color;
65. this.nation = nation;
66.     }
67. }
1. public enum Color {
2. /**
3.      * 红色,绿色,蓝色
4.      */
5.     RED("红色"),GREEN("绿色"),Blue("蓝色");
6. private final String co;
7. 
8.     Color(String co) {
9. this.co = co;
10.     }
11. public String getCo() {
12. return co;
13.     }
14. }

2、向集合中加入数据,开始处理list集合

1. Apple apple1 = new Apple("Apple1", 32.23, Color.RED, "china");
2. Apple apple2 = new Apple("Apple2", 23, Color.RED, "japan");
3. Apple apple3 = new Apple("Apple3", 12.09, Color.GREEN, "america");
4. Apple apple4 = new Apple("Apple4", 43.12, Color.Blue, "english");
5. Apple apple5 = new Apple("Apple5", 12.09, Color.GREEN, "oss");
6. Apple apple6 = new Apple("Apple6", 12.09, Color.GREEN, "fsd");
7. Apple apple7 = new Apple("Apple7", 12.09, Color.Blue, "fa");
8. Apple apple8 = new Apple("Apple8", 12.09, Color.Blue, "as");
9. Apple apple9 = new Apple("Apple9", 10.232, Color.GREEN, "sfs");
10. Apple apple10 = new Apple("Apple10", 43.22, Color.RED, "zz");
11. List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4, apple5, apple6, apple7, apple8, apple9, apple10);

案例1:按照重量排序,重量一样时候按照城市排序

list.sort(Comparator.comparing(Apple::getWeight).thenComparing(Apple::getNation));

案例2:筛选要么是重量大于23的红苹果,要么是绿苹果的集合

1. // 方式一
2. Predicate<Apple> predicate = apple -> Color.RED.equals(apple.getColor());
3. list.stream().filter(predicate.and(a -> a.getWeight() > 23).or(b -> b.getColor().equals(Color.GREEN))).forEach(System.out::println);
4. // 方式二
5. list.stream().filter(apple -> Color.RED.equals(apple.getColor()) && apple.getWeight() > 23 || Color.GREEN.equals(apple.getColor())).forEach(System.out::println);

案例3:挑选重量小于30的苹果,然后按照城市名字排序,并把名字打印出来

list.stream().filter(apple -> apple.getWeight() < 30).map(Apple::getNation).sorted().forEach(System.out::println);

案例4:筛选前二个红苹果

appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).limit(2).forEach(System.out::println);

案例5:筛选除了前两个的其他所有红苹果

appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).skip(2).forEach(System.out::println);

案例6:遍历所有每个苹果所在城市名字的长度

appleList.stream().map(apple -> apple.getNation().length()).forEach(System.out::println);

案例7:找到任意一个红苹果(第一个、是否全是红,是否有一个红色,是否没有红)

1. // 任意一个红苹果
2. appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).findAny().ifPresent(System.out::println);
3. // 第一个红苹果
4. Optional<Apple> first = appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).findFirst();
5. System.out.println(first.orElse(new Apple("11", 23, Color.RED, "lalalla")));
6. // 是否全是红
7. System.out.println(appleList.stream().allMatch(apple -> Color.RED.equals(apple.getColor())));
8. // 是否有红
9. System.out.println(appleList.stream().anyMatch(apple -> Color.RED.equals(apple.getColor())));
10. // 是否没有红
11. System.out.println(appleList.stream().noneMatch(apple -> Color.RED.equals(apple.getColor())));

案例8:计算所有苹果的重量和

1. // 方式一
2. System.out.println(appleList.stream().mapToDouble(Apple::getWeight).reduce(0.00, (a, b) ->
3. // 为了防止小数位过多
4. new BigDecimal(Double.toString(a)).add(new BigDecimal(Double.toString(b))).doubleValue()
5. ));
6. // 方式二
7. System.out.println(appleList.stream().mapToDouble(Apple::getWeight).sum());

案例9:找出最重的苹果

1. // 方式一
2. appleList.stream().map(Apple::getWeight).reduce(Double::max).ifPresent(System.out::println);
3. // 方式二
4. appleList.stream().max(Comparator.comparingDouble(Apple::getWeight)).ifPresent(apple -> System.out.println(apple.getWeight()));
5. // 方式三
6. appleList.stream().mapToDouble(Apple::getWeight).max().ifPresent(System.out::println);

案例10:返回所有的城市名字字符串,按照城市名字排序

1. System.out.println(appleList.stream().map(Apple::getNation)
2.         .distinct()
3.         .sorted()
4. // 效率不高
5. //.reduce("", (a, b) -> a + b));
6.         .collect(Collectors.joining(",")));

案例11:求出平均重量

1. // 方式一
2. appleList.stream().mapToDouble(Apple::getWeight).average().ifPresent(System.out::println);
3. // 方式二
4. System.out.println(appleList.stream().collect(Collectors.averagingDouble(Apple::getWeight)));

案例12:按照苹果颜色分组,颜色一样按照重量分组

Map<Color, Map<Double, List<Apple>>> collect = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.groupingBy(Apple::getWeight)));

案例13:按照颜色分组,并且显示每种颜色分组后的数量

1. Map<Color, Long> collect = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.counting()));
2. collect.entrySet().forEach(System.out::println);
3. // 补充,假如挑选所要结果后大于3的
4. collect.entrySet().stream().filter(colorLongEntry -> colorLongEntry.getValue() > 3).forEach(System.out::println);

案例14:按颜色分组,挑选出每个分组中重量最大的,重量一样的话,根据城市名字

1. Map<Color, Optional<Apple>> collect = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.maxBy(Comparator.comparingDouble(Apple::getWeight).thenComparing(Apple::getNation))));
2. // 去掉optional
3. Map<Color, Apple> collect1 = collect.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, colorOptionalEntry -> colorOptionalEntry.getValue().orElse(new Apple()), (a, b) -> a));
4. System.out.println(collect1);
5. // 方式二
6. //Map<Color, Apple> collect3 = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingDouble(Apple::getWeight).thenComparing(Apple::getNation)), Optional::get)));
7. Map<Color, Apple> collect2 = appleList.stream().collect(Collectors.toMap(Apple::getColor, Function.identity(), BinaryOperator.maxBy(Comparator.comparingDouble(Apple::getWeight).thenComparing((Apple::getNation)))));
8. System.out.println("-----------------------------");
9. System.out.println(collect2);

案例15:同时找出苹果的总数量,最大值,最小值,平均值

1. DoubleSummaryStatistics collect = appleList.stream().collect(Collectors.summarizingDouble(Apple::getWeight));
2. System.out.println(collect);

案例16:按照颜色分组,找出每个分组下的最大值,总数。最小值,平均值

1. Map<Color, DoubleSummaryStatistics> collect1 = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.summarizingDouble(Apple::getWeight)));
2. collect1.entrySet().forEach(System.out::println);

案例17:重量大于20的分为一组,重量小于20的分为一组

1. // 方式一
2.  Map<Boolean, List<Apple>> collect = appleList.stream().collect(Collectors.groupingBy(a -> a.getWeight() > 20));
3.  collect.forEach((aBoolean, apples) -> System.out.println(aBoolean + apples.toString()));
4. // 方式二
5.  Map<Boolean, List<Apple>> collect1 = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20));
6.  collect1.forEach((aBoolean, apples) -> System.out.println(aBoolean + apples.toString()));

案例18:基于案例17,每种分组再按照颜色分组

1. Map<Boolean, Map<Color, List<Apple>>> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.groupingBy(Apple::getColor)));
2. System.out.println(collect);

案例19:重量大于20的分为一组,重量小于20的分为一组,只要分组的重量最大的

Map<Boolean, Apple> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingDouble(Apple::getWeight)), Optional::get)));

案例20:按照重量大于20的一组,小于20的一组,找出每组个数

Map<Boolean, Long> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.counting()));

案例21:先根据重量是否大于20分组,再根据颜色是否为红色分组

Map<Boolean, Map<Boolean, List<Apple>>> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.partitioningBy(apple -> apple.getColor().equals(Color.RED))));

案例22:根据名字降序排序,为null的在最后

appleList.sort(Comparator.comparing(Apple::getName,Comparator.nullsLast(Comparator.reverseOrder())));

扩充知识:

1. public static void main(String[] args) {
2. // 生成1-100的偶数流
3. //test1();
4. // 生成1-100内的勾股数
5. //test2();
6. // iterate打印10个偶数
7. //test3();
8. // 生成10个斐波那契数列
9. //test4();
10. //生成随机数或者全是1的无限流
11. //test5();
12.     }
13. public static void test1(){
14. // 打印个数(注意,rangeClosed包括两端,range不包括右端点)
15.       IntStream.rangeClosed(1, 100).filter(value -> value % 2 == 0).forEach(System.out::println);
16.     }
17. public static void test2(){
18.         IntStream.rangeClosed(1,100).boxed().flatMap(
19.                 a->IntStream.rangeClosed(a,100).mapToObj(b->new double[]{a,b,Math.sqrt(a*a+b*b)})
20.         ).filter(t->t[2]%1==0).forEach(result->System.out.println(result[0]+""+result[1]+result[2]));
21.     }
22. public static void test3(){
23.         Stream.iterate(0,a->a+2).limit(10).forEach(System.out::println);
24.     }
25. public static void test4(){
26.         Stream.iterate(new int[]{0,1},a->new int[]{a[1],a[0]+a[1]}).limit(10).forEach(result-> System.out.println(result[0]));
27.     }
28. public static void test5(){
29. // 生成随机数
30.         Stream.generate(Math::random).limit(20).forEach(System.out::println);
31. // 生成全是1的无限流
32.         Stream.generate(()->1).limit(20).forEach(System.out::println);
33.     }
34. }


目录
相关文章
|
21小时前
|
Java API
【JAVA进阶篇教学】第三篇:JDK8中Stream API使用
【JAVA进阶篇教学】第三篇:JDK8中Stream API使用
|
1天前
|
缓存 Java 数据库
Java并发编程学习11-任务执行演示
【5月更文挑战第4天】本篇将结合任务执行和 Executor 框架的基础知识,演示一些不同版本的任务执行Demo,并且每个版本都实现了不同程度的并发性。
17 4
Java并发编程学习11-任务执行演示
|
1天前
|
设计模式 消息中间件 安全
【Java多线程】关于多线程的一些案例 —— 单例模式中的饿汉模式和懒汉模式以及阻塞队列
【Java多线程】关于多线程的一些案例 —— 单例模式中的饿汉模式和懒汉模式以及阻塞队列
8 0
|
2天前
|
数据库连接
java+ssm+vue代码视频学习讲解
java+ssm+vue代码视频学习讲解
5 0
|
3天前
|
数据采集 机器学习/深度学习 Java
数据猎手:使用Java和Apache HttpComponents库下载Facebook图像
本文介绍了如何使用Java和Apache HttpComponents库从Facebook获取图像数据。通过设置爬虫代理IP以避免限制,利用HttpClient发送请求,解析HTML找到图像链接,然后下载并保存图片。提供的Java代码示例展示了实现过程,包括创建代理配置、线程池,以及下载图片的逻辑。注意,实际应用需根据Facebook页面结构进行调整。
数据猎手:使用Java和Apache HttpComponents库下载Facebook图像
|
9天前
|
存储 监控 Java
如何在Java中实现等待文件修改后再读取数据的功能?
如何在Java中实现等待文件修改后再读取数据的功能?
15 0
|
9天前
|
分布式计算 Java API
Java 8新特性之Lambda表达式与Stream API
【5月更文挑战第1天】本文将介绍Java 8中的两个重要特性:Lambda表达式和Stream API。Lambda表达式是一种新的函数式编程语法,可以简化代码并提高可读性。Stream API是一种用于处理集合的新工具,可以方便地进行数据操作和转换。通过结合Lambda表达式和Stream API,我们可以更加简洁高效地编写Java代码。
|
10天前
|
Java 关系型数据库 测试技术
Java代码一键生成数据库文档(案例详解)
Screw是一个自动化数据库文档生成工具,能根据数据库表结构快速生成简洁、多格式(HTML、Word、Markdown)的文档,支持MySQL、MariaDB等多数据库。它使用Freemarker模板,允许用户自定义样式。依赖包括HikariCP数据库连接池和对应JDBC驱动。通过在Java代码或Maven插件中配置,可方便生成文档。示例代码展示了如何在测试用例中使用Screw。文档效果依赖于数据库中的表和字段注释。
|
10天前
|
Java
Java8 Stream Collectors groupingBy使用
Java8 Stream Collectors groupingBy使用
|
11天前
|
算法 Java 大数据
Java从入门到精通学习报告
Java从入门到精通学习报告
19 1