Java8 Stream实例--统计出所有含‘张’字的人员的平均年龄

时间:2021-02-02 12:51:23
package com.zhangxueliang.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream; public class Lambda_Stream_Demo {
public static void main(String[] args){
//method1();
List<Student> list = createStudent();
double d = list.stream()
.filter(s->s.getName().indexOf("张")>=0)
.mapToDouble(s->s.getAge())
.average()
.getAsDouble();
System.out.println("包含张字的所有人的平均年龄为:"+ d);
}
private static void method1() {
List<Student> list = createStudent();
Stream<Student> stream = list.stream();
stream.filter(s->s.getGender()==Student.Sex.FEMALE).forEach(s->System.out.println(s.toString()));
}
public static List<Student> createStudent(){
Student s1 = new Student("张三",16,Student.Sex.MALE);
Student s2 = new Student("张四",18,Student.Sex.FEMALE);
Student s3 = new Student("王五",26,Student.Sex.MALE);
Student s4 = new Student("赵柳",36,Student.Sex.FEMALE);
List<Student> ss = new ArrayList<Student>();
ss.add(s1);
ss.add(s2);
ss.add(s3);
ss.add(s4);
return ss;
}
}