Stream实现List和Map互转总结

前言

本篇介绍Stream流List和Map互转,同时在转换过程中遇到的问题分析。

一、Map转List

1.1 分析

按照默认顺序
1
java复制代码mapToList.entrySet().stream().map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
根据key排序
1
java复制代码mapToList.entrySet().stream().sorted(Comparator.comparing(a -> a.getKey())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
根据key排序
1
java复制代码mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
根据key倒序排序
1
java复制代码mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
根据value排序
1
java复制代码mapToList.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
根据value倒序排序
1
java复制代码mapToList.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());

1.2 完整代码

实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
java复制代码/**
* @author lilinchao
* @date 2021/7/28
* @description 1.0
**/
public class User {
private Integer id;
private String name;

public User() {
}

public User(Integer id, String name) {
this.id = id;
this.name = name;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
Map转List代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
java复制代码import java.util.*;
import java.util.stream.Collectors;

/**
* @author lilinchao
* @date 2021/7/28
* @description 1.0
**/
public class StreamMapToList {

/**
* 数据初始化
*/
private static final Map<Integer, String> mapToList;
static
{
mapToList = new HashMap<Integer, String>();
mapToList.put(1003, "Thymee");
mapToList.put(1001, "Leefs");
mapToList.put(1002, "Jeyoo");
}
public static void main(String ages[]){
List<User> userList = defaultOrder();
System.out.println(userList);
List<User> userList2and = orderByKeyMethodOne();
System.out.println(userList2and);
List<User> userList3and = orderByKeyMethodTwo();
System.out.println(userList3and);
List<User> userList4and = reverseOrderByKey();
System.out.println(userList4and);
List<User> userList5and = orderByValue();
System.out.println(userList5and);
List<User> userList6and = reverseOrderByValue();
System.out.println(userList6and);
}

/**
* 按照默认顺序
*/
public static List<User> defaultOrder(){
List<User> userList = mapToList.entrySet().stream().map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
return userList;
}
/**
*根据key排序,方法1
*/
public static List<User> orderByKeyMethodOne(){
List<User> userList = mapToList.entrySet().stream().sorted(Comparator.comparing(a -> a.getKey())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
return userList;
}
/**
*根据key排序,方法2
*/
public static List<User> orderByKeyMethodTwo(){
List<User> userList = mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
return userList;
}
/**
*根据key倒序排序
*/
public static List<User> reverseOrderByKey(){
List<User> userList = mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
return userList;
}
/**
* 根据value排序
*/
public static List<User> orderByValue(){
List<User> userList = mapToList.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
return userList;
}
/**
*根据value倒序排序
*/
public static List<User> reverseOrderByValue(){
List<User> userList = mapToList.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
return userList;
}
}
运行结果
1
2
3
4
5
6
json复制代码[User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}, User{id=1003, name='Thymee'}]
[User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}, User{id=1003, name='Thymee'}]
[User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}, User{id=1003, name='Thymee'}]
[User{id=1003, name='Thymee'}, User{id=1002, name='Jeyoo'}, User{id=1001, name='Leefs'}]
[User{id=1002, name='Jeyoo'}, User{id=1001, name='Leefs'}, User{id=1003, name='Thymee'}]
[User{id=1003, name='Thymee'}, User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}]

二、List转Map

2.1 分析

指定key-value,value是对象中的某个属性值
1
java复制代码userList.stream().collect(Collectors.toMap(User::getId, User::getName));
指定key-value,value是对象本身

User->User 是一个返回本身的lambda表达式

1
java复制代码userList.stream().collect(Collectors.toMap(User::getId, User->User));
指定key-value,value是对象本身

Function.identity()是简洁写法,也是返回对象本身

1
java复制代码userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
指定key-value,key 冲突的解决办法

(key1,key2)->key2:第二个key覆盖第一个key
(key1,key2)->key1:保留第一个key

1
java复制代码userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));

2.2 完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
java复制代码import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author lilinchao
* @date 2021/7/28
* @description 1.0
**/
public class StreamListToMap {

private static final List<User> userList;
static
{
userList = Arrays.asList(
new User(1003,"keko"),
new User(1001,"jeek"),
new User(1002,"mack")
);
}

public static void main(String ages[]){

Map<Integer, String> map = method01();
System.out.println(map);
Map<Integer, User> map2and = method02();
System.out.println(map2and);
Map<Integer, User> map3and = method03();
System.out.println(map3and);
Map<Integer, User> map4and = method04();
System.out.println(map4and);
}

/**
* 指定key-value,value是对象中的某个属性值
*/
public static Map<Integer,String> method01(){
Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getName));
return userMap;
}
/**
*指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式
*/
public static Map<Integer,User> method02(){
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, User->User));
return userMap;
}
/**
* 指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身
*/
public static Map<Integer,User> method03(){
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
return userMap;
}
/**
* 指定key-value,key 冲突的解决办法
* (key1,key2)->key2:第二个key覆盖第一个key
* (key1,key2)->key1:保留第一个key
*/
public static Map<Integer,User> method04(){
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
return userMap;
}
}
运行结果
1
2
3
4
json复制代码{1001=jeek, 1002=mack, 1003=keko}
{1001=User{id=1001, name='jeek'}, 1002=User{id=1002, name='mack'}, 1003=User{id=1003, name='keko'}}
{1001=User{id=1001, name='jeek'}, 1002=User{id=1002, name='mack'}, 1003=User{id=1003, name='keko'}}
{1001=User{id=1001, name='jeek'}, 1002=User{id=1002, name='mack'}, 1003=User{id=1003, name='keko'}}

三、List转Map常见问题

3.1 常见问题

问题一

报错Duplicate key xxxx

该问题是因为在生成Map集合时key值重复造成的

解决方案

1. 后面的value覆盖前面的value

1
java复制代码userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key2));

也可以保留前面的value,将key2换成key1即可

2. value进行拼接

1
java复制代码userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key1+","+key2));

3. key重复时,返回集合

1
2
3
4
5
6
7
8
9
10
java复制代码userList2and.stream().collect(Collectors.toMap(User::getId, p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
));
问题二

报错:Exception in thread "main" java.lang.NullPointerException

该问题是因为在存入Map集合时value值为null

解决方案

在转换流中加上判空,即便value为空,依旧输出。(与上面方法三相同)

3.2 完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
java复制代码import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author lilinchao
* @date 2021/7/28
* @description 1.0
**/
public class StreamListToMapAnalyze {

private static final List<User> userList;
private static final List<User> userList2and;
static
{
//重复的key
userList = Arrays.asList(
new User(1003,"keko"),
new User(1001,"jeek"),
new User(1001,"teek"),
new User(1002,"mack")
);
//重复的key,value为null
userList2and = Arrays.asList(
new User(1003,"keko"),
new User(1001,"jeek"),
new User(1001,"teek"),
new User(1002,null)
);
}

public static void main(String ages[]){
Map<Integer, String> map = keyRepeatMethod01();
System.out.println(map);
Map<Integer, String> map2and = keyRepeatMethod02();
System.out.println(map2and);
Map<Integer,List<String>> map3and = keyRepeatMethod03();
System.out.println(map3and);
}

/**
* key重复时,后面的value覆盖前面的value
*/
public static Map<Integer,String> keyRepeatMethod01(){
Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key2));
return userMap;
}
/**
* key重复时,value进行拼接
*/
public static Map<Integer,String> keyRepeatMethod02(){
Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key1+","+key2));
return userMap;
}
/**
* key重复时,返回集合
* value值为空,在转换流中加上判空,即便value为空,依旧输出
*/
public static Map<Integer,List<String>> keyRepeatMethod03(){
Map<Integer, List<String>> userListMap = userList2and.stream().collect(Collectors.toMap(User::getId, p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
));
return userListMap;
}
}
运行结果
1
2
3
json复制代码{1001=teek, 1002=mack, 1003=keko}
{1001=jeek,teek, 1002=mack, 1003=keko}
{1001=[jeek, teek], 1002=[null], 1003=[keko]}

附:参考文章链接

www.cnblogs.com/fugitive/p/…

www.jb51.net/article/170…

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%