阅读量:0
class MyObject { Long id; String name; // Constructor public MyObject(Long id, String name) { this.id = id; this.name = name; } // Getters public Long getId() { return id; } public String getName() { return name; } }
第一种 List 转 Map<Long, String>
List<MyObject> myObjectList=new ArrayList<>(); // 自行赋值 Map<Long, String> map = myObjectList.stream() .collect(Collectors.toMap( MyObject::getId, // key mapper MyObject::getName// value mapper ));
第二种 List 转 Map<Long, List>
List<MyObject> myObjectList=new ArrayList<>(); // 自行赋值 Map<Long, List<String>> map = myObjectList.stream() .collect(Collectors.groupingBy( MyObject::getId, // key mapper Collectors.mapping(MyObject::getName, Collectors.toList()) // value mapper ));