1.简单转换Map<String, String>
package com;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List<ExcelEntity> list = new ArrayList<>();
ExcelEntity entity1 = new ExcelEntity();
entity1.setGlobalNo("001");
entity1.setUserId("zhangsan");
entity1.setAddress("北京");
entity1.setGoodsCd("A001");
list.add(entity1);
ExcelEntity entity2 = new ExcelEntity();
entity2.setGlobalNo("002");
entity2.setUserId("lisi");
entity2.setAddress("上海");
entity2.setGoodsCd("A002");
list.add(entity2);
ExcelEntity entity3 = new ExcelEntity();
entity3.setGlobalNo("003");
entity3.setUserId("wangwu");
entity3.setAddress("辽宁");
entity3.setGoodsCd("A003");
list.add(entity3);
Map<String, String> map1 = list.stream()
.collect(Collectors.toMap(ExcelEntity::getGlobalNo, ExcelEntity::getUserId));
System.out.println(map1);
// {001=zhangsan, 002=lisi, 003=wangwu}
}
}
list 的 getGlobalNo 会做为新Map的Key,getUserId 做为新Map的Value。
注意:ExcelEntity名称必须是list的泛型,名称不可变
但是还有另一种写法:
Map<String, String> map1 = list.stream()
.collect(Collectors.toMap(obj -> obj.getGlobalNo(), obj -> obj.getUserId()));
注意:此时 getGlobalNo 后面必须加 ()
2.Map有重复key
Map有重复key时会报错:java.lang.IllegalStateException: Duplicate key zhangsan
Map<String, String> map1 = list.stream()
.collect(Collectors.toMap(ExcelEntity::getGlobalNo, ExcelEntity::getUserId, (o, n) -> n));
可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
可以用 (o, n) -> n 来设置,如果有重复的key时,则保留 n(新的没,即还没有放到map里的),舍弃 o(旧的)
3.转换成Map<String, ExcelEntity>
Map<String, ExcelEntity> map1 = list.stream()
.collect(Collectors.toMap(ExcelEntity::getGlobalNo, Function.identity(), (o, n) -> n));
System.out.println(map1);
// {001=com.ExcelEntity@7cd62f43, 002=com.ExcelEntity@6d4b1c02, 003=com.ExcelEntity@6093dd95}
当然还有另一种写法:
Map<String, ExcelEntity> map1 = list.stream()
.collect(Collectors.toMap(ExcelEntity::getGlobalNo, obj -> obj, (o, n) -> n));
当然也可以用groupingBy或者partitioningBy进行转换