/* 1) javabean类
学生类 姓名 年龄 性别 小区
小区类 地址 小区名 总人数
性别类 男 女
*/
ArrayList<StreamStudent> list = new ArrayList<>();
list.add(new StreamStudent("小王", 21, new StreamSex("男"), new StreamCommunity("上海", "海德堡", 200)));
list.add(new StreamStudent("小李", 22, new StreamSex("男"), new StreamCommunity("天津", "3区", 215)));
list.add(new StreamStudent("小赵", 23, new StreamSex("女"), new StreamCommunity("北京", "海德堡", 3121)));
list.add(new StreamStudent("小白", 24, new StreamSex("男"), new StreamCommunity("南京", "阳光丽兹", 2111)));
list.add(new StreamStudent("小王", 22, new StreamSex("男"), new StreamCommunity("上海", "2区", 982)));
// 1. 汇总小区名为"海德堡"的学生的总数;
int sum = list.stream()
.filter(e -> e.getStreamCommunity().getCommuntityName().equals("海德堡"))
.mapToInt(a -> a.getStreamCommunity().getSum())
.sum();
System.out.println(sum);
// 2. 汇总小区名为"海德堡"的学生的姓名集合;
list.stream()
.filter(e -> e.getStreamCommunity().getCommuntityName().equals("海德堡"))
.map(StreamStudent::getName)
.forEach(System.out::println);
// 3. 返回住在阳光丽兹+海德堡的学生的平均年龄;
OptionalDouble average = list.stream()
.filter(e ->
e.getStreamCommunity().getCommuntityName().equals("海德堡") || e.getStreamCommunity().getCommuntityName().equals("阳光丽兹")
)
.mapToInt(e -> e.getAge()).average();
System.out.println(average);
// 4.拿到年龄大于平均年龄的所有学生的姓名集合;
double average1 = list.stream()
.mapToInt(StreamStudent::getAge)
.average().getAsDouble();
System.out.println(average1);
list.stream()
.filter(e -> e.getAge() > average1)
.map(streamStudent -> streamStudent.getName())
.forEach(System.out::println);
for (StreamStudent e : list) {
if (e.getAge() > average1) {
String name = e.getName();
System.out.println(name);
}
}
}
Java8 新特性 - Stream流相关函数练习题(二)
于 2023-02-14 16:15:04 首次发布
该代码示例展示了如何使用JavaStreamAPI来处理学生列表,包括过滤、映射和聚合操作。具体任务包括统计特定小区的学生总数、打印指定小区学生姓名、计算特定小区学生的平均年龄以及找出年龄大于平均年龄的学生姓名。
摘要由CSDN通过智能技术生成