• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

Java-Map-merge

Java SE 来源:半笙彷徨 1次浏览

JAVA8中Map新增了merge方法,文档解释:

public V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction) Description copied from interface: 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 null. This method may be of use when combining multiple mapped values for a key. For example, to either create or append a String msg to a value mapping: map.merge(key, msg, String::concat) If the function returns null the mapping is removed. If the function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged. Specified by: merge in interface Map<K,V> Parameters: key - key with which the resulting value is to be associated 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 remappingFunction - the function to recompute a value if present Returns: the new value associated with the specified key, or null if no value is associated with the key

大意是:如果给定key没绑定值或值为null,则绑定给定值,否则,执行重映射方法替换原来值或者删除原来的值。

注意:就是说如果key没冲突的话就直接设置到map中,发生冲突则合并或删除冲突key,所以key每冲突时不会执行remappingFunction里的代码。


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)