java8中利用stream api将list转成map

Region{
    string: code;
    string: label;
    string: parentCode;
    //set/get 
}
List<Region> cityList= getRegionList();

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

猜你喜欢

转载自hzwei206.iteye.com/blog/2362195