JDK8 Map新函数merge()的学习理解

自己用JDK8也有蛮久了。里面加了些什么东西我都没好好去了解,今天学了点皮毛。记录一下:

Map里的新函数,源码如下:

/**
 * If the specified key is not already associated with a value or is
 * associated with null, associates it with the given non-null value.
 * Otherwise, replaces the associated value with the results of the given
 * remapping function, or removes if the result is {@code null}. This
 * method may be of use when combining multiple mapped values for a key.
 * For example, to either create or append a {@code String msg} to a
 * value mapping:
 *
 * <pre> {@code
 * map.merge(key, msg, String::concat)
 * }</pre>
 *
 * <p>If the function returns {@code null} the mapping is removed.  If the
 * function itself throws an (unchecked) exception, the exception is
 * rethrown, and the current mapping is left unchanged.
 *
 * @implSpec
 * The default implementation is equivalent to performing the following
 * steps for this {@code map}, then returning the current value or
 * {@code null} if absent:
 *
 * <pre> {@code
 * V oldValue = map.get(key);
 * V newValue = (oldValue == null) ? value :
 *              remappingFunction.apply(oldValue, value);
 * if (newValue == null)
 *     map.remove(key);
 * else
 *     map.put(key, newValue);
 * }</pre>
 *
 * <p>The default implementation makes no guarantees about synchronization
 * or atomicity properties of this method. Any implementation providing
 * atomicity guarantees must override this method and document its
 * concurrency properties. In particular, all implementations of
 * subinterface {@link java.util.concurrent.ConcurrentMap} must document
 * whether the function is applied once atomically only if the value is not
 * present.
 *
 * @param key key with which the resulting value is to be associated
 * @param value the non-null value to be merged with the existing value
 *        associated with the key or, if no existing value or a null value
 *        is associated with the key, to be associated with the key
 * @param remappingFunction the function to recompute a value if present
 * @return the new value associated with the specified key, or null if no
 *         value is associated with the key
 * @throws UnsupportedOperationException if the {@code put} operation
 *         is not supported by this map
 *         (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
 * @throws ClassCastException if the class of the specified key or value
 *         prevents it from being stored in this map
 *         (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)
 * @throws NullPointerException if the specified key is null and this map
 *         does not support null keys or the value or remappingFunction is
 *         null
 * @since 1.8
 */
default V merge(K key, V value,
        BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
    Objects.requireNonNull(remappingFunction);
    Objects.requireNonNull(value);
    V oldValue = get(key);
    V newValue = (oldValue == null) ? value :
               remappingFunction.apply(oldValue, value);
    if(newValue == null) {
        remove(key);
    } else {
        put(key, newValue);
    }
    return newValue;
}

 注释说的大概意思是可以把旧值进行合并、删除、更新等操作。今天也在网上稍微充查了点资料。才对这个函数有所了解。

1.//准备测试数据
List<File> files = Arrays.asList(
        new File("1.txt"),
        new File("2.txt"),
        new File("3.txt")
);

2.文件内容大概是这样

3.把文件里的数据全部装进来一个Map里。然后通过合并函数统计每个字母出现的次数

List<Map<String,Integer>> results=new ArrayList<>();
files.parallelStream().forEach(file -> {
    try {
        Map<String, Integer> count = count(file);
        results.add(count);
    } catch (IOException e) {
        e.printStackTrace();
    }
});
    Map<String,Integer> finalResults=new HashMap<>();
    for (Map<String,Integer>result:results) {
        finalResults.putAll(merge(finalResults,result));
    }
    System.out.println(finalResults);
}
public static Map<String,Integer> count(File file) throws IOException {
    //文件工具类读取所有行的内容
    List<String> strings = Files.readAllLines(file.toPath());
    //
    Map<String,Integer> stringIntegerMap=new HashMap<>();

    for (String line:strings) {
        String[] split = line.split("\\s+");
        for (String s:split){
                if(s.equals(""))continue;
                int count = stringIntegerMap.getOrDefault(s, 0);
                stringIntegerMap.put(s,count+1);
        }
    }
    return stringIntegerMap;
}

//合并Map
private static Map<String, Integer> merge(Map<String, Integer> toMap,Map<String, Integer> curMap){
    curMap.forEach((key,value) -> toMap.merge(key,value,Integer::sum));
    return toMap;
}
//覆盖Map
private static Map<String, Integer> merge(Map<String, Integer> toMap,Map<String, Integer> curMap){
    curMap.forEach((key,value) -> toMap.merge(key,value,(oldV,newV)->newV));
    return toMap;
}
//删除Map
private static Map<String, Integer> merge(Map<String, Integer> toMap,Map<String, Integer> curMap){
    curMap.forEach((key,value) -> toMap.merge(key,value,(oldV,newV)->null));
    return toMap;
}

4.得到的统计数据。

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值