• java8 运算语法集


    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));
  • 相关阅读:
    The Best Seat in ACM Contest
    确定比赛名次
    Red and Black
    Can you find it?
    胜利大逃亡
    Reward
    DXUT编译指南(转)
    逐顶点和逐像素光照
    转战DX
    hlsl之ambient
  • 原文地址:https://www.cnblogs.com/kingsonfu/p/9859061.html
Copyright © 2020-2023  润新知