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. }


目录
打赏
0
0
0
0
4
分享
相关文章
Java爬虫获取微店快递费用item_fee API接口数据实现
本文介绍如何使用Java开发爬虫程序,通过微店API接口获取商品快递费用(item_fee)数据。主要内容包括:微店API接口的使用方法、Java爬虫技术背景、需求分析和技术选型。具体实现步骤为:发送HTTP请求获取数据、解析JSON格式的响应并提取快递费用信息,最后将结果存储到本地文件中。文中还提供了完整的代码示例,并提醒开发者注意授权令牌、接口频率限制及数据合法性等问题。
|
24天前
|
使用Java和Spring Data构建数据访问层
本文介绍了如何使用 Java 和 Spring Data 构建数据访问层的完整过程。通过创建实体类、存储库接口、服务类和控制器类,实现了对数据库的基本操作。这种方法不仅简化了数据访问层的开发,还提高了代码的可维护性和可读性。通过合理使用 Spring Data 提供的功能,可以大幅提升开发效率。
64 21
Java线程池ExecutorService学习和使用
通过学习和使用Java中的 `ExecutorService`,可以显著提升并发编程的效率和代码的可维护性。合理配置线程池参数,结合实际应用场景,可以实现高效、可靠的并发处理。希望本文提供的示例和思路能够帮助开发者深入理解并应用 `ExecutorService`,实现更高效的并发程序。
36 10
深潜数据海洋:Java文件读写全面解析与实战指南
通过本文的详细解析与实战示例,您可以系统地掌握Java中各种文件读写操作,从基本的读写到高效的NIO操作,再到文件复制、移动和删除。希望这些内容能够帮助您在实际项目中处理文件数据,提高开发效率和代码质量。
13 0
【潜意识Java】深度分析黑马项目《苍穹外卖》在Java学习中的重要性
《苍穹外卖》项目对Java学习至关重要。它涵盖了用户管理、商品查询、订单处理等模块,涉及Spring Boot、MyBatis、Redis等技术栈。
115 4
【潜意识Java】深入理解MyBatis的Mapper层,以及让数据访问更高效的详细分析
深入理解MyBatis的Mapper层,以及让数据访问更高效的详细分析
81 1
【潜意识Java】Java基础教程:从零开始的学习之旅
本文介绍了 Java 编程语言的基础知识,涵盖从简介、程序结构到面向对象编程的核心概念。首先,Java 是一种高级、跨平台的面向对象语言,支持“一次编写,到处运行”。接着,文章详细讲解了 Java 程序的基本结构,包括包声明、导入语句、类声明和 main 方法。随后,深入探讨了基础语法,如数据类型、变量、控制结构、方法和数组。此外,还介绍了面向对象编程的关键概念,例如类与对象、继承和多态。最后,针对常见的编程错误提供了调试技巧,并总结了学习 Java 的重要性和方法。适合初学者逐步掌握 Java 编程。
54 1
【Java技术指南】「Java8技术盲区」在奔向Java13的同时,也让我们仔细研究一下Stream的学习认知!
【Java技术指南】「Java8技术盲区」在奔向Java13的同时,也让我们仔细研究一下Stream的学习认知!
160 0
【Java技术指南】「Java8技术盲区」在奔向Java13的同时,也让我们仔细研究一下Stream的学习认知!
Java 8 Stream API学习总结
Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
1055 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等