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)));
// JAVA8 新特性 - stream流各种用法(遍历、最大、最小、平均值、分组、求和、过滤、排序)
//遍历所以学生信息
list.stream().forEach(System.out::println);
System.out.println('\n');
//年龄最大的同学姓名
String name = list.stream()
.max(Comparator.comparing(StreamStudent::getAge))
.map(StreamStudent::getName).get();
System.out.println(name);
System.out.println('\n');
//年龄最小的同学年龄
Integer integer = list.stream()
.map(StreamStudent::getAge)
.reduce(Integer::min)
.get();
System.out.println(integer);
System.out.println('\n');
//所以人年龄平均值
double asDouble = list.stream()
.mapToInt(StreamStudent::getAge)
.average().getAsDouble();
System.out.println(asDouble);
System.out.println('\n');
//按年龄分组
Map<Integer, List<StreamStudent>> map = list.stream()
.collect(Collectors.groupingBy(StreamStudent::getAge));
map.forEach((key, val) -> {
System.out.println(key + " " + val);
});
System.out.println('\n');
//所以同学所住小区的人数总和
int sum = list.stream()
.mapToInt(e -> e.getStreamCommunity().getSum()).sum();
System.out.println(sum);
System.out.println('\n');
//筛选年龄为21和22的同学
list.stream()
.filter(e -> e.getAge() == 21 || e.getAge() == 22)
.forEach(System.out::println);
System.out.println('\n');
//将所以同学按年龄从大到小排序并遍历
list.stream()
.sorted(Comparator.comparing(StreamStudent::getAge).reversed())
.forEach(System.out::println);
JAVA8 新特性 - stream流各种用法(遍历、最大、最小、平均值、分组、求和、过滤、排序)
最新推荐文章于 2024-05-16 10:23:10 发布