Map<String, String> map = list.stream().collect( Collectors.toMap(Student :: getClassName, Student :: getStudentName, (key1 , key2)-> key2 )); 也可以简写成这样: Map<String, String> map = list.stream().collect( Collectors.toMap(Student :: getClassName, Student :: getStudentName, (...
list.add(student1); list.add(student2); list.add(student3); Map<String, Integer> map = list.stream() .collect(Collectors.toMap(Student::getName, Student::getAge)); 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 方式一存在的问题 Collectors.toMap()调用的方法如下: public static <T, K, U...
//2、list转map 指定key-value,key为属性值,value是对象本身 Map<String,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User)); System.out.println("2->"+userMap2); //3、list转map 指定key-value,value是对象本身,Function.identity()是简洁写法,返回对象本身 Map<...
import java.util.Map; import java.util.stream.Collectors;public class Java08 { public static void main(String[] args) {// List集合转换为Map集合(k,v) List<Person> list = new ArrayList<Person>(); list.add(new Person("张三", 30)); list.add(new Person("李四", 40)); list.add(new ...
1.List转Map class A 方式一: Map<String, A> aMap = aList.stream().collect(Collectors.toMap(A::getId, a -> a)); 也可以使用Function接口中的一个默认方法 Function.identity(),这个方法返回自身对象 方式二: Map<String, A> aMap = aList.stream().collect(Collectors.toMap(A::getId, Function....
在JDK 8中,将List对象转换为Map对象是一个常见的操作,可以通过Java 8的Stream API和Collectors工具类来实现。以下是如何完成这一操作的详细步骤和示例代码: 1. 确定List中对象的属性 首先,你需要确定List中对象的属性,这些属性将用于Map的键和值。例如,假设你有一个Person类,包含name和age两个属性,你可以选择将na...
2、以ID(id+userName)为Key,用户对象为Value构建Map(key为NULL时报错) Map<Long, User> map = users.stream().collect(Collectors.toMap(User::getId, Function.identity())); Map<String, User> map = users.stream().collect(Collectors.toMap(user -> String.valueof(user.getId() + user.getUserName(...
4、List转换为Map public clasygcmfms Hosting { private int Id; private String name; private long websites; public Hosting(int id, String name, long websites) { Id = id; this.name = name; this.websites = websites; } //getters, setters and toString() ...
publicstaticvoidmain(String[]args){//将List转换为MapMap<Integer,User>userMap=users.stream().collect(Collectors.toMap(User::getId,Function.identity()));System.out.println(JSON.toJSONString(userMap));} 效果一览: null:{"edu":"004","schoolId":400,"userName":"小5"},3001:{"edu":"003","...