前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【面试题精讲】如何使用Stream的聚合功能

【面试题精讲】如何使用Stream的聚合功能

作者头像
程序员朱永胜
发布2023-09-09 14:18:05
1520
发布2023-09-09 14:18:05
举报

有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top

首发博客地址

系列文章地址

求和(Sum):
代码语言:javascript
复制
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum: " + sum);
  1. 求平均值(Average):
代码语言:javascript
复制
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
System.out.println("Average: " + average);
  1. 最大值(Max):
代码语言:javascript
复制
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int max = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);
System.out.println("Max: " + max);
  1. 最小值(Min):
代码语言:javascript
复制
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int min = numbers.stream().mapToInt(Integer::intValue).min().orElse(0);
System.out.println("Min: " + min);
  1. 计数(Count):可以使用 count()方法来计算Stream中元素的个数。
代码语言:javascript
复制
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().count();
System.out.println("Count: " + count);
  1. 连接字符串(Joining):可以使用 collect()方法结合 Collectors.joining()来将Stream中的元素连接成一个字符串。
代码语言:javascript
复制
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
String joinedNames = names.stream().collect(Collectors.joining(", "));
System.out.println("Joined Names: " + joinedNames);
  1. 分组(Grouping):可以使用 collect()方法结合 Collectors.groupingBy()来根据某个属性对Stream中的元素进行分组。
代码语言:javascript
复制
List<Person> people = Arrays.asList(
    new Person("Alice", 25),
    new Person("Bob", 30),
    new Person("Charlie", 25)
);
Map<Integer, List<Person>> peopleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge));
System.out.println("People grouped by age: " + peopleByAge);
  1. 求和(Summarizing):可以使用 collect()方法结合 Collectors.summarizingInt()等方法来获取元素的汇总信息,如求和、平均值、最大值、最小值等。
代码语言:javascript
复制
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
IntSummaryStatistics stats = numbers.stream().collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Sum: " + stats.getSum());
System.out.println("Average: " + stats.getAverage());
System.out.println("Max: " + stats.getMax());
System.out.println("Min: " + stats.getMin());
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-09-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档