通过Function转换list和map


list转换到map

1
2
3
4
5
6
7
public static <K, V> Map<K, V> listToMap(List<V> list, Function<V, K> function) {
Map<K, V> map = new HashMap<>();
for (V object : list) {
map.put(function.apply(object), object);
}
return map;
}

map转换到list

1
2
3
4
5
6
7
public static <K, V, T> Map<K, T> listToMap(List<V> list, Function<V, K> keyFunction, Function<V, T> valueFunction) {
Map<K, T> map = new HashMap<>();
for (V object : list) {
map.put(keyFunction.apply(object), valueFunction.apply(object));
}
return map;
}