1. 程式人生 > >java8 分組並進行求和組合運算

java8 分組並進行求和組合運算

color long pri ray aslist 進行 ads nbsp 示例

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}

2、List轉換成Map

示例主要代碼:

Map<Long, AdSlotData> adPVNumMap = adSlotDataList.stream()
                .collect(Collectors.toMap(AdSlotData::getSlotId, adSlotData -> adSlotData, (k1, k2) -> k1));

java8 分組並進行求和組合運算