computeIfAbsent是Java 8引入的Map接口中的一个方法

computeIfAbsent是Java 8引入的Map接口中的一个方法,它提供了一种更高效且线程安全的方式来 conditionally compute or retrieve a value for a given key in a map. 当你想要为一个键计算一个值(如果该键尚不存在对应的映射关系),并且仅当该键还没有关联的值时才执行计算时,这个方法非常有用。

方法签名如下:

V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)
  • K 是Map中键的类型。
  • V 是Map中值的类型。
  • key 是你想要检查和/或插入值的键。
  • mappingFunction 是一个函数,当给定的键在Map中不存在时会被调用。这个函数接受键作为参数,并返回应该与该键关联的值。

如果key在Map中已经存在,则该方法直接返回当前与该键关联的值,而不会执行mappingFunction。如果key不存在,那么mappingFunction会被调用,其结果会被插入到Map中与key关联,并返回这个新计算的值。


在提供的代码示例中,computeIfAbsent确保了如果dataMap中还没有与key相关的映射,就创建一个新的HashMap并与之关联。这样可以避免因重复的key导致的多次put操作,提高了效率,同时也简化了代码。

    private void addInfluxDbChannelHistoryDataToTheMap(List<FluxTable> fluxTableList, Map<String, Map<Integer, String>> dataMap) {
        fluxTableList.stream()
            .flatMap(fluxTable -> fluxTable.getRecords().stream())
            .forEach(record -> {
                String channelIdWithDeviceId = Optional.ofNullable(String.valueOf(record.getValueByKey("channelIdWithDeviceId")))
                    .orElseThrow(() -> new IllegalArgumentException("channelIdWithDeviceId is missing"));
                String deviceId = channelIdWithDeviceId.split("_")[0];

                String timeStr = Optional.ofNullable(String.valueOf(record.getValueByKey("_time")))
                    .orElseThrow(() -> new IllegalArgumentException("_time is missing"));
                String time = influxDBUtils.convertIsoToCustomFormat(timeStr, DateUtils.YYYY_MM_DD_HH_MM_SS);

                String key = deviceId + "_" + time;
                Integer cid = Optional.ofNullable(record.getValueByKey("cid"))
                    .map(Object::toString)
                    .filter(s -> !s.equals("null"))
                    .map(Integer::valueOf)
                    .orElseThrow(() -> new IllegalArgumentException("cid is invalid"));

                String value = Optional.ofNullable(String.valueOf(record.getValueByKey("value")))
                    .orElse("");

                dataMap.computeIfAbsent(key, k -> new HashMap<>()).put(cid, value);
            });
    }

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值