1、map转list
public class MapToList {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("张3", 20);
map.put("李4", 19);
map.put("王5", 18);
List<User> collect = map.entrySet().stream().map(user -> new User(user.getKey(), user.getValue())).sorted().collect(Collectors.toList());
collect.stream().forEach(n -> System.out.println(n));
}
}
2、list转map
package com.guoyuan.blog;
import com.guoyuan.pojo.Student;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMap {
List<Student> list = Arrays.asList(
new Student(1, 18, "张3"),
new Student(2, 19, "李4"),
new Student(3, 19, "王5")
);
@Test
public void listToMapByObject() {
Map<Integer, Student> map = list.stream().collect(Collectors.toMap(Student::getId, student -> student));
// 遍历打印结果
map.forEach((key, value) -> {
System.out.println("key: " + key + " value: " + value);
});
}
@Test
public void listToMapByName() {
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Student::getId, Student::getName));
// 遍历打印结果
map.forEach((key, value) -> {
System.out.println("key: " + key + " value: " + value);
});
}
@Test
public void listToMapByAge() {
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Student::getAge, Student::getName));
}
@Test
public void listToMapByAgeKey() {
// value 为对象中的属性
Map<Integer, String> map = list.stream().collect(
Collectors.toMap(Student::getAge, Student::getName, (key1, key2) -> key1)
);
map.forEach((key, value) -> {
System.out.println("key: " + key + " value: " + value);
});
}
}
listToMapByObject()结果:
key: 1 value: Student{id=1, age=18, name='张3'}
key: 2 value: Student{id=2, age=19, name='李4'}
key: 3 value: Student{id=3, age=19, name='王5'}
//Student实体类中没有重写toString会出现:
key: 1 value: com.guoyuan.pojo.Student@326de728
key: 2 value: com.guoyuan.pojo.Student@25618e91
key: 3 value: com.guoyuan.pojo.Student@7a92922
listToMapByName()结果:
key: 1 value: 张3
key: 2 value: 李4
key: 3 value: 王5
//Student实体类中没有重写toString没有影响
listToMapByAge()结果:
注:map的key必须唯一,所以有可能出现不唯一的时候,就会报错
java.lang.IllegalStateException: Duplicate key 李4
listToMapByAgeKey()结果是:
注:此时stream包下Collectors.toMap方法有一个重载方法的参数,这个参数可以传一个合并的函数解决冲突
key: 18 value: 张3
key: 19 value: 李4
原文出处:https://blog.csdn.net/icannotdebug/article/details/78621705