创建一个学生实体类,当然不太规范,只是为了将一些可能用到的数据装入:
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class StudentDto {
/**
* 学生id
*/
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<StudentDto> studentList = new ArrayList<>();
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、遍历并返回一个集合:
List<StudentDto> students = studentList.stream
.flatMap(it -> {
return it;
}).collect(Collectors.toList());
4、统计男生数量:
int num = (int) studentList.stream().filter(it -> it.getSex == "男").count();
5、根据班级分组:
Map<String, List<StudentDto>> 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();
版权声明:本文为qq_41061437原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。