将List转为Map并key去重

2021-12-07 16:43:44 浏览数 (1)

需求:将查询出的List转换为Map,且使用List中的某个字段为主键去重。

eg:查询出的学生list,将学生根据性别为key,Name为value转为map,由于性别是只有男/女,且map的key不可以重复,哪么我们需要使用Group By对key进行去重。

代码语言:javascript复制
        Map<Integer, List<String>> collect = studentList.stream()
                .collect(Collectors.groupingBy(Student::getSex, Collectors.mapping(Student::getName, Collectors.toList())));
代码语言:javascript复制
@Test
public void test7() {
    List<Student> studentList = new ArrayList<>();
    studentList.add(new Student("张三",1));
    studentList.add(new Student("李四",2));
    studentList.add(new Student("王五",1));
    studentList.add(new Student("小六",1));
    studentList.add(new Student("张三S",2));
    Map<Integer, List<String>> collect = studentList.stream()
            .collect(Collectors.groupingBy(Student::getSex, Collectors.mapping(Student::getName, Collectors.toList())));
}

class Student {
    private String name;
    private Integer sex;

    public String getName() {
        return name;
    }

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

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Student(String name, Integer sex) {
        this.name = name;
        this.sex = sex;
    }
}

补充:如需要一个Key对应多个Value的数据结构,建议使用MultiValueMap

0 人点赞