
- 一. Collectors.toMap
- 二. 事例
- 三. List转Map
看看源码
public staticCollector > toMap(Function super T, ? extends K> keyMapper, Function super T, ? extends U> valueMapper, BinaryOperator mergeFunction) { return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new); }
有三个参数,还有个默认参数
参数含义:
- keyMapper:Key 的映射函数 - valueMapper:Value 的映射函数 - mergeFunction:当 Key 冲突时,调用的处理方法 - mapSupplier:Map 构造器,在需要返回特定的 Map 时使用二. 事例
输入
public static void main(String[] args) {
List testList = Lists.newArrayList(
new TestEntity().setId(1).setName("张三"),
new TestEntity().setId(1).setName("李四"), // Key 相同
new TestEntity().setId(2).setName("王五")
);
Map map = testList.stream()
.collect(Collectors.toMap(TestEntity::getId, TestEntity::getName, (n1, n2) -> n1 + n2));
System.out.println("map:" + map);
}
输出
输入
public static void main(String[] args) {
List testList = Lists.newArrayList(
new TestEntity().setId(1).setName("张三"),
new TestEntity().setId(1).setName("李四"), // Key 相同
new TestEntity().setId(2).setName("王五")
);
Map map = testList.stream()
.collect(Collectors.toMap(TestEntity::getId, TestEntity::getName, (n1, n2) -> n1 + n2));
System.out.println("map:" + map);
Map> mapList = testList.stream()
.collect(Collectors.toMap(TestEntity::getId, item -> {
List list = Lists.newArrayList();
list.add(item);
return list;
}, (n1, n2) -> {
n1.addAll(n2);
return n1;
}));
System.out.println("map:" + mapList);
}
输出
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)