用Collectors的toMap方法转换List,一般会遇到两个问题。
- 转换map,key重复问题;
1.重复时用后面的value 覆盖前面的value
2.重复时将前面的value 和后面的value拼接起来;
3.重复时将重复key的数据组成集合
- 另一个是空指针异常,即转为map的value是null
package core.stream;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMapTest {
private List<Student> list ;
@Before
public void setUp() {
list = Arrays.asList(new Student(1, 18, "阿龙"),
new Student(2, 17, "小花"),
new Student(3, 17, "阿浪"));
}
/**
* key:Object
* {1=Student(id=1, age=18, name=阿龙), 2=Student(id=2, age=17, name=小花), 3=Student(id=3, age=17, name=阿浪)}
*/
@Test
public void testListToMapByObjectValue() {
Map<Integer, Student> map = list.stream().collect(Collectors.toMap(Student::getId, student -> student));
System.out.println(map);
}
/**
* Key:value
* {1=阿龙, 2=小花, 3=阿浪}
*/
@Test
public void testListToMapByNameValue() {
List<Student> list = Arrays.asList(new Student(1, 18, "阿龙"),
new Student(2, 17, "小花"),
new Student(3, 17, "阿浪"));
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(map);
}
/**
*重复时将前面的value和后面的value拼接起来
*例如:按年龄分组统计用户
*{17=小花,阿浪, 18=阿龙}
*/
@Test
public void testListToMapByNameValueConcatenation() {
Map<Integer,String> map = list.stream().collect(
Collectors.toMap(Student::getAge,Student::getName,
(key1,key2)-> key1+","+key2));
System.out.println(map);
}
/**
* 重复时将重复的key的数据组成集合
* 例如:按年龄分组统计用户
* {17=[小花, 阿浪], 18=[阿龙]}
*/
@Test
public void testListToMapByNameList() {
Map<Integer,List<String>> map = list.stream().collect(
Collectors.toMap(Student::getAge, p -> {
List<String> values = new ArrayList<>();
values.add(p.getName());
return values;
},(List<String> value1,List<String> value2)->{
value1.addAll(value2);
return value1;
}));
System.out.println(map);
}
}
package core.stream;
import lombok.Data;
@Data
public class Student {
private int id;
private int age;
private String name;
public Student(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}