java8最简单的list列表转换成map类型

list列表转换成map结构

方法一:

Map<Integer, Student> mapStream = studentList.stream().collect(Collectors.toMap(Student::getNumber, Student -> Student));

方法二:

Map<Integer, Student> studentMap = new HashMap<>();
studentList.forEach(a -> studentMap.put(a.getNumber(), a));

具体实例:

import model.Student;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : null
 * @date : 2019/1/10
 * @description:
 */
public class ListToMap {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        Student student = new Student();
        student.setName("第一位");
        student.setNumber(1);
        studentList.add(student);
        Student student1 = new Student();
        student1.setNumber(2);
        student1.setName("第二位");
        studentList.add(student1);

        //方法一
        Map<Integer, Student> mapStream = studentList.stream().collect(Collectors.toMap(Student::getNumber, Student -> Student));
        System.out.println(mapStream.get(1).getName());
        System.out.println(mapStream.get(2).getName());

        System.out.println("+++++++++++++++++分割线+++++++++++++++++++++");
        //方法二
        Map<Integer, Student> studentMap = new HashMap<>();
        studentList.forEach(a -> studentMap.put(a.getNumber(), a));
        System.out.println(studentMap.get(1).getName());
        System.out.println(studentMap.get(2).getName());
    }
}

附属类

/**
 * @author : null
 * @date : 2018/11/20
 * @description:
 */
public class Student{

    private String name;
    private Integer number;
    private Teacher teacher;

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }
}

输出结果:

第一位
第二位
+++++++++++++++++分割线+++++++++++++++++++++
第一位
第二位

 

    原文作者:Mint6
    原文地址: https://blog.csdn.net/mint6/article/details/86222822
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞