没有比正直更富的遗产。——莎士比亚

我们在使用JDK自带的Collectors.toMap时,可能会遇到如下问题(什么?你不知道toMap干嘛的?戳我了解):

1.key重复,出现java.lang.IllegalStateException: Duplicate key ***异常

例如:

1
2
List<User> users = new ArrayList<>(Arrays.asList(new User(null, "HiNo"), new User(null, "SuPa")));
Map<String, String> map = users.stream().collect(Collectors.toMap(User::getUsername, User::getPassword));

2.value为空,出现NPE: java.lang.NullPointerException

例如:

1
2
List<User> users = new ArrayList<>(Arrays.asList(new User("SuPa", null), new User("HiNo", null)));
Map<String, String> map = users.stream().collect(Collectors.toMap(User::getUsername, User::getPassword));

这里我们可以不使用Collectors,而是直接在collect中传入参数

1
Map<String, String> map = users.stream().collect(HashMap::new, (m, v) -> m.put(v.getUsername(), v.getPassword()), HashMap::putAll);

或者是在后面追加参数,例如我这篇博客

这样确实可以解决,但每次都要写这一长串,有点难受——本人比较懒,所以写一个工具类

这里是直接put进去,所以不存在说key重复或者为NPE问题

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SerializedLambda;
import com.ruben.pojo.User;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

/**
* @ClassName: FunctionUtils
* @Description: 我还没有写描述
* @Date: 2020/11/9 0009 23:43
* *
* @author: <achao1441470436@gmail.com>
* @version: 1.0
* @since: JDK 1.8
*/
public class FunctionUtils {

/**
* @MethodName: toHashMap
* @Description: list -> hashMap
* @Date: 2021/1/31 0031 16:17
* *
* @author: <achao1441470436@gmail.com>
* @param: [list, keyFunction, valueFunction]
* @returnValue: java.util.Map<K, U>
*/
public static <T, K, U> Map<K, U> toHashMap(List<T> list, Function<T, K> keyFunction, Function<T, U> valueFunction) {
if (Objects.isNull(list) || list.isEmpty()) {
return new HashMap<>(0);
}
return list.stream().collect(MyCollectors.toHashMap(keyFunction, valueFunction));
}

public static <T, K> Map<K, T> toHashMap(List<T> list, Function<T, K> keyFunction) {
return toHashMap(list, keyFunction, null);
}

public static <T> Map<?, T> toHashMap(List<T> list) {
return toHashMap(list, null, null);
}

/**
* @ClassName: MyCollectors
* @Date: 2020/12/4 0004 11:16
* @Description: 我的自定义Collectors
* @Author: <achao1441470436@gmail.com>
*/
public static class MyCollectors {
/**
* @MethodName: toHashMap
* @Description: 转换成hashmap
* @Date: 2020/12/4 0004 13:39
* *
* @author: <achao1441470436@gmail.com>
* @param: [methodName]
* @returnValue: java.util.stream.Collector
*/
public static <T, K, U> Collector<T, HashMap<K, U>, HashMap<K, U>> toHashMap(Function<T, K> keyFunction, Function<T, U> valueFunction) {
return new MyCollectorImpl<>(HashMap::new, (m, v) -> m.put(Optional.ofNullable(keyFunction).map(keyF -> keyF.apply(v)).orElseGet(() -> {
try {
return (K) v.getClass().getMethod("getId").invoke(v);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}), Optional.ofNullable(valueFunction).map(valueF -> valueF.apply(v)).orElse((U) v)), (u, v) -> null, i -> i, Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)));
}

public static class MyCollectorImpl<T, A, R> implements Collector<T, A, R> {
private final Supplier<A> supplier;
private final BiConsumer<A, T> accumulator;
private final BinaryOperator<A> combiner;
private final Function<A, R> finisher;
private final Set<Characteristics> characteristics;

MyCollectorImpl(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Function<A, R> finisher,
Set<Characteristics> characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}

@Override
public Supplier<A> supplier() {
return supplier;
}

@Override
public BiConsumer<A, T> accumulator() {
return accumulator;
}

@Override
public BinaryOperator<A> combiner() {
return combiner;
}

@Override
public Function<A, R> finisher() {
return finisher;
}

@Override
public Set<Characteristics> characteristics() {
return characteristics;
}
}
}
}

使用方式(注意返回值):

指定keyvalue使用它本身

1
Map<String, User> map = toHashMap(users, User::getUsername);

指定keyvalue

1
Map<String, String> map = toHashMap(users, User::getUsername, User::getPassword);

默认不指定,keyidvalue为它本身的方式(需要有id属性并包含getter

1
2
3
Map<?, User> map = toHashMap(users);
// 可以强转
Map<Integer, User> map = (Map<Integer, User>) toHashMap(users);