1、分组并进行求和组合运算
示例主要代码:
List<String> items = Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya"); Map<String, Long> result = items.stream().collect( Collectors.groupingBy( Function.identity(), Collectors.counting() ) ); System.out.println(result);
运行结果如下:
{papaya=1, orange=1, banana=2, apple=3}
或者针对对象的复杂处理:
/** * * 先按slotId进行分组,再对分好组之后的数据进行求和 *
*/
Map<Long, Long> adNumMap = adSlotDataList.stream()
.collect(Collectors.groupingBy(AdSlotData::getSlotId, Collectors.summingLong(AdSlotData::getAdNum)));
2、List转换成Map
示例主要代码:
/** * List -> Map * 需要注意的是: * toMap 如果集合对象有重复的key,会报错Duplicate key ....
* apple1,apple12的id都为1。 * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2 */
Map<Long, AdSlotData> adPVNumMap = adSlotDataList.stream()
.collect(Collectors.toMap(AdSlotData::getSlotId, adSlotData -> adSlotData, (k1, k2) -> k1));