java8中利用stream api将list转成map

阅读更多
Region{
    string: code;
    string: label;
    string: parentCode;
    //set/get 
}
List cityList= getRegionList();

//转成Map
Map map = cityList.stream().collect(Collectors.toMap(Region::getCode, item->item));
 
或者
Map map = cityList.stream().collect(Collectors.toMap(Region::getCode, Function.identity()));
 
上面两个转换在code重复时会报错,改成:
Map map = cityList.stream().collect(Collectors.toMap(Region::getCode, Function.identity(), (k1, k2)->k2));
 
或者转成指定实现类的map:
Map map = cityList.stream().collect(Collectors.toMap(Region::getCode, Function.identity(), (k1, k2)->k2, LinkedHashMap::new));
 
//分组:转成Map>
Map> map2 = cityList.stream().collect(Collectors.groupingBy(Region::getParentCode));
 
//分组:转成Map>
Map> map3 = cityList.stream().collect(Collectors.groupingBy(Region::getParentCode, Collectors.mapping(Region::getCode, Collectors.toList())));
 
//分组:计算每个parentCode对应的集合元素个数:Map
Map map3 = cityList.stream().collect(Collectors.groupingBy(Region::getParentCode, Collectors.counting()));
 
 

你可能感兴趣的:(java8,stream,List转Map)