java list 转map方法

list转map三种方法

public class Student{

private Long studentId;

private String studentName;

(setget 方法省略)

}

(1)最原始方法用for循环方法进行处理

Map List2Map(List dataList){

Map map = new HashMap();

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 List2Map(List 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 List2Map(List dataList){

Map map = new HashMap();

if(dataList == null || dataList.isEmpty()){

return map;

}

map =  Maps.uniqueIndex(dataList,new com.google.common.base.Function() {

@Nullable

@Override

    public String apply(@Nullable Student student) {

return student.getStudentId();

}

});

}

你可能感兴趣的:(java list 转map方法)