package com.liupei.java8; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class ListToMap { public static void main(String[] args) { List<Stu> stuList = new ArrayList<Stu>(); //方式一 Map<String, String> stringMap = stuList.stream().collect(Collectors.toMap(v -> String.valueOf(v.getId()), v -> v.getName())); //方式二 Map<Long, String> stringMap2 = stuList.stream().collect(Collectors.toMap(Stu::getId, Stu::getName)); //转换成map的时候,可能出现key一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。 // 转成map的时候,最好使用下面的方式: Map<Long, Stu> maps = stuList.stream().collect(Collectors.toMap(Stu::getId, Function.identity(), (key1, key2) -> key2)); Map<Long, String> maps1 = stuList.stream().collect(Collectors.toMap(Stu::getId, Stu::getName, (key1, key2) -> key2)); //List 以ID分组 Map Map<Long, List<Stu>> groupBy = stuList.stream().collect(Collectors.groupingBy(Stu::getId)); } } class Stu { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }