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);});}