注意事项
Collectors.toMap
key:不能有两个相同的key,可以为null(多个值对应一个key)
value:可以有相同的value,但value不能为null
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Collectors.toMap
* key:不能有两个相同的key,可以为null(多个值对应一个key)
* value:可以有相同的value,但value不能为null
*/
public class MyTest {
@Test
void test0() {
List<User> userList = new ArrayList<>();
// 不能有两个相同的key
userList.add(new User("张三", "18"));
userList.add(new User("张三", "19"));
userList.stream().collect(Collectors.toMap(User::getName, User::getAge));
}
@Test
void test1() {
List<User> userList = new ArrayList<>();
// value 不能为null
userList.add(new User("王五", null));
userList.stream().collect(Collectors.toMap(User::getName, User::getAge));
}
@Test
void test2() {
List<User> userList = new ArrayList<>();
// key可以为null,value可以重复
userList.add(new User(null, "18"));
userList.add(new User("李四", "null"));
userList.add(new User("王五", "null"));
Map<String, String> nameAgeMap = userList.stream().collect(Collectors.toMap(User::getName, User::getAge));
System.out.println(nameAgeMap.get(null));
}
@Test
void test3() {
List<User> userList = new ArrayList<>();
// 对象不能为null
userList.add(null);
Map<String, String> nameAgeMap = userList.stream().collect(Collectors.toMap(User::getName, User::getAge));
System.out.println(nameAgeMap.get(null));
}
class User {
private String name;
private String age;
public User(String name, String age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
}
标签:map,toMap,Collectors,userList,User,new,null
From: https://www.cnblogs.com/miefind/p/18348304