Java8 根据一个字段进行分组
public class ListGroupBy {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList .add(new User().setNum("001").setYear("2018").setScore(100.0).setTime(2088-08-09));
userList .add(new User().setNum("001").setYear("2019").setScore(59.5).setTime(2088-08-09));
userList .add(new User().setNum("001").setYear("2019").setScore(99.0).setTime(2088-08-09));
userList .add(new User().setNum("002").setYear("2021").setScore(99.6).setTime(2088-08-09));
Map<String, List<user>> map = scoreList.stream().collect(
Collectors.groupingBy(
e-> e.setYear()
));
System.out.println(JSONUtil.toJsonPrettyStr(map));
}
}
分组排序
Map<String, List<User>> map = scoreList.stream().collect(
Collectors.groupingBy(
e-> e.getYear(),LinkedHashMap::new,Collectors.toList()
));
多个字段分组
Map<String, List<User>> map = scoreList.stream().collect(
Collectors.groupingBy(
e-> e.getYear()+'-'+e.getNum()
));
转换时间格式为key 例如 kyy:2022-06-08
Map<String, List<user>> map = scoreList.stream().collect(
Collectors.groupingBy(
e-> new SimpleDateFormat("yyyy-MM-dd").format(User.getTime())
));
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bfbb3713492fc3880e2a60b1bb34f13e.png)