Java 8中List转Map

@Data
public class Student {
   //学号
    private  String no;  
    //姓名
    private  String name;	
}
 
@Data
public class Teacher{
    //教师号
    private  String no; 
    //姓名 
    private  String name; 
}

一、List 转 Map

//声明一个List集合
List<Student> list = new ArrayList();  
	 list.add(new Student("1001", "小A"));  
	 list.add(new Student("1001", "小B"));//学号重复(下面特殊处理)
	 list.add(new Student("1002", "小C"));
	 list.add(new Student("1003", "小D"));
       
//将list转map 【key为1个属性,value为1个属性】  
Map<String, String> map =
	list.stream().collect(Collectors.toMap( 
		Student::getNo, 
		Student::getName,
	    (key1 , key2) -> key1  //(map的键重复不会报错,下面已经处理)
	));
	
//将list转map 【key为多个属性,value为1个属性】  
Map<String, String> map =
	list.stream().collect(Collectors.toMap( 
		obj -> obj.getNo() + "_" + obj.getName(),
		Student::getName,
	    (key1 , key2) -> key1   //(map的键重复不会报错,下面已经处理)
));

二、List 转 Map (返回对象本身)

//声明一个List集合
List<Student> list = new ArrayList();
	list.add(new Student("1001", "小A"));
	list.add(new Student("1001", "小B"));
	list.add(new Student("1002", "小C"));
	list.add(new Student("1003", "小D"));
 
//将list转map 【key为1个属性,value为对象本身】  (map的键去重)
Map<String, Student> map = 
 	list.stream().collect(Collectors.toMap( 
	 	Student::getNo, 
	    obj -> obj, 
	    (key1 , key2) -> key1 
    ));
    
或者
 
//将list转map 【key为1个属性,value为对象本身】  (map的键去重)
Map<String, Student> map = 
 	list.stream().collect(Collectors.toMap( 
	 	Student::getNo, 
	    Function.identity(), 
	    (key1 , key2) -> key1 
));
    
或者
 
//将list转map 【key为多个属性,value为对象本身】 (map的键去重)
Map<String, Student> map = 
 	list.stream().collect(Collectors.toMap( 
	 	obj -> obj.getNo() + "_" + obj.getName(),
	    obj -> obj, 
	    (key1 , key2) -> key1 
    ));
	

三、List 转 Map (返回另一个对象)

//声明一个List集合
List<Student> list = new ArrayList();
	list.add(new Student("1001", "小A"));
	list.add(new Student("1001", "小B"));
	list.add(new Student("1002", "小C"));
	list.add(new Student("1003", "小D"));
 
//将list转map 【key为1个属性,value为另一个对象】 (map的键去重)
Map<String, Teacher> map = 
	list.stream().collect(Collectors.toMap(
	    Student::getNo, 
		stu -> {
            Teacher teacher = new Teacher();
            teacher.setNo(stu.getNo());
            teacher.setName(stu.getName());
            return teacher;
        },  
        (key1 , key2) -> key1
));

四、List 转 Map (分组)【以1个字段分/以多个字段分】

//声明一个List集合
List<Student> list = new ArrayList();
   list.add(new Student("1001", "小A"));
   list.add(new Student("1001", "小B"));
   list.add(new Student("1002", "小C"));
   list.add(new Student("1003", "小D"));
 
//将list转map  【key为1个属性,value为相同key的集合】 (以某1个属性来分组,将分组后相同的对象放在一起)
Map<String, List<Student>> map = 
   list.stream().collect( Collectors.groupingBy(Student::getNo) );
 
 
//将list转map 【key为多个属性,value为相同key的集合】 (以多个属性来分组,将分组后相同的对象放在一起)
Map<String, List<Student>> map = 
   list.stream().collect( Collectors.groupingBy(obj -> obj.getNo + "_" + obj.getName) );
 

你可能感兴趣的:(java)