LIst转Map
泛型为Map
@GetMapping("/test")
public Object test() {
List<Map<Integer, Integer>> list = Lists.newArrayList();
for (int i = 1; i <= 3; i++) {
Map<Integer, Integer> m = new HashMap<>();
m.put(i, i);
list.add(m);
}
Map<Integer, Integer> map = list.stream().flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldVal, newVal) -> newVal));
return map;
}
泛型为对象
@GetMapping("/test")
public Object test() {
List<MyClass> list = Lists.newArrayList();
for (int i = 1; i <= 3; i++) {
MyClass myClass = new MyClass();
myClass.setKey(i);
myClass.setVal(i);
list.add(myClass);
}
Map<Integer, Integer> map = list.stream().collect(Collectors.toMap(MyClass::getKey, MyClass::getVal, (oldVal, newVal) -> newVal));
return map;
}
@Data
static class MyClass {
private Integer key;
private Integer val;
}
key相同处理
在使用Collectors.toMap()
方法时,如果存在重复的key
,会导致报错,因此可以通过传入的第三个参数
来处理相同key的情况。
(oldVal, newVal) -> newVal
key相同,保留新值(oldVal, newVal) -> oldVal
key相同,保留旧值(oldVal, newVal) -> oldVal + newVal
key相同,旧值新值相加(如果是串旧值新值拼接)
// [{"key":"A","val":1},{"key":"B","val":2},{"key":"B","val":3}]
List<MyClass> list = Lists.newArrayList();
// {"A":1,"B":3}
Map<String, Integer> map1 = list.stream().collect(Collectors.toMap(MyClass::getKey, MyClass::getVal, (oldVal, newVal) -> newVal));
// {"A":1,"B":2}
Map<String, Integer> map2 = list.stream().collect(Collectors.toMap(MyClass::getKey, MyClass::getVal, (oldVal, newVal) -> oldVal));
// {"A":1,"B":5}
Map<String, Integer> map3 = list.stream().collect(Collectors.toMap(MyClass::getKey, MyClass::getVal, (oldVal, newVal) -> oldVal + newVal));
Map转List
泛型为对象
@GetMapping("/test")
public Object test() {
Map<Integer, Integer> m = new HashMap<>();
for (int i = 1; i <= 3; i++) {
m.put(i, i);
}
List<MyClass> list = m.entrySet().stream()
.map(e -> {
MyClass myClass = new MyClass();
myClass.setKey(e.getKey());
myClass.setVal(e.getValue());
return myClass;
}).collect(Collectors.toList());
return list;
}
@Data
static class MyClass {
private Integer key;
private Integer val;
}
泛型为Map
@GetMapping("/test")
public Object test() {
Map<Integer, Integer> m = new HashMap<>();
for (int i = 1; i <= 3; i++) {
m.put(i, i);
}
List<Map<Integer, Integer>> list = m.entrySet().stream()
.map(e -> {
Map<Integer, Integer> map = new HashMap<>();
map.put(e.getKey(), e.getValue());
return map;
}).collect(Collectors.toList());
return list;
}