list转map三种方法
public class Student{
private Long studentId;
private String studentName;
(setget 方法省略)
}
(1)最原始方法用for循环方法进行处理
Map<Long,Student> List2Map(List<Student> dataList){
Map<Long,Student> map = new HashMap<Long,Student>();
if(dataList == null || dataList.isEmpty()){
return map;
}
for(Student student :dataList ){
map.put(student.getStudentId,student);
}
return map;
}
(2)使用java8提供的流方法(注意如果Spring框架版本为4.0以下与java8版本不兼容,使用会报错)
Map<Long,Student> List2Map(List<Student> dataList){
Map map = new HashMap();
if(dataList == null || dataList.isEmpty()){
return map;
}
map = dataList.stream().collect(Collectors.toMap(Student:getStudentId,s->s));
return map;
}
(3)使用google的guava工具
Map<Long,Student> List2Map(List<Student> dataList){
Map<Long,Student> map = new HashMap<Long,Student>();
if(dataList == null || dataList.isEmpty()){
return map;
}
map = Maps.uniqueIndex(dataList,new com.google.common.base.Function<Student,Long>() {
@Nullable
@Override
public String apply(@Nullable Student student) {
return student.getStudentId();
}
});
}