Java8之后很多新特性,接下来主要讲一下, list集合利用stream根据对象得某一属性对集合进行分组!
话不多说,上代码:
首先准备实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer id;
private String name;
//成绩
private Double score;
}
然后开始写测试类:
import java.util.*;
import java.util.stream.Collectors;
public class GroupByName {
public static void main(String[] args) {
//准备要分组得集合
List<Student> students = Arrays.asList(
new Student(1,"伽罗",99d),
new Student(2,"后羿",97d),
new Student(3,"鲁班",98d),
new Student(4,"后羿",90d),
new Student(5,"百里",88d),
new Student(6,"狼狗",59d),
new Student(7,"艾琳",78d),
new Student(8,"伽罗",94d)
);
//jdk8.0新特性来分组,根据学生姓名来进行分组
Map<String,List<Student>> result = new HashMap<>();
result = students.stream().collect(Collectors.groupingBy(Student::getName));
result.forEach((x,y) -> System.out.println(x+"--"+y));
System.out.println("华丽分割线"+"------------------------");
//jdk1.8之前手写分组
Map<String,List<Student>> map = new HashMap<>();
for (Student student : students) {
List<Student> list = map.get(student.getName());
if (list == null) {
list = new ArrayList<>();
list.add(student);
map.put(student.getName(), list);
} else {
list.add(student);
}
}
map.forEach((x,y) -> System.out.println(x+"--"+y));
/**
* 结果:
* 伽罗--[Student(id=1, name=伽罗, score=99.0), Student(id=8, name=伽罗, score=94.0)]
* 百里--[Student(id=5, name=百里, score=88.0)]
* 狼狗--[Student(id=6, name=狼狗, score=59.0)]
* 艾琳--[Student(id=7, name=艾琳, score=78.0)]
* 后羿--[Student(id=2, name=后羿, score=97.0), Student(id=4, name=后羿, score=90.0)]
* 鲁班--[Student(id=3, name=鲁班, score=98.0)]
*/
}
}
到这里新特性分组就介绍完了,列子简单,直接上手简单,谢谢大家支持!!