栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

Java8中List、Map的使用

Java 更新时间:发布时间: 百科书网 趣学号

创建一个学生实体类,当然不太规范,只是为了将一些可能用到的数据装入:

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 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 students = 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();

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/956941.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号