
创建一个学生实体类,当然不太规范,只是为了将一些可能用到的数据装入:
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class StudentDto {
private Integer id;
private String userName;
private String sex;
private String className;
private Integer age;
private float height;
private float weight;
private BigDecimal score;
private Date createAt;
}
这里统一集合为List
1、forEach遍历:
studentList.forEach(it -> {
System.out.println(it.getUserName);
});
2、forEach遍历过滤年龄大于20岁的并输出:
studentList.stream
.filter(it -> it.getAge <= 20)
.forEach(it -> {
System.out.println(it.getUserName);
});
3、遍历并返回一个集合:
Liststudents = studentList.stream .flatMap(it -> { return it; }).collect(Collectors.toList());
4、统计男生数量:
int num = (int) studentList.stream().filter(it -> it.getSex == "男").count();
5、根据班级分组:
Map> studentMap = studentList.stream().collect(Collectors.groupingBy(StudentDto::getClassName));
6、对第5根据班级分组的结果进行遍历,及对Map进行遍历:
studentMap.forEach((key, value) -> {
System.out.println("key=" + key);
System.out.println("value=" + value);
});
7、计算所有学生的总分,即对BigDecimal进行计算:
studentList.stream().map(StudentDto::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
8、计算总分均值:
studentList.stream().map(StudentDto::getScore).reduce(BigDecimal.ZERO, BigDecimal::add).divide(new BigDecimal(studentList.size()), 10, RoundingMode.HALF_UP);
9、求分数最大值最小值:
// 最大 studentList.stream().map(StudentDto::getScore).max((o1, o2) -> o1.compareTo(o2)).get(); // 最小 studentList.stream().map(StudentDto::getScore).min((o1, o2) -> o1.compareTo(o2)).get();