您现在的位置是:首页 > 文章详情

JAVA8 MAP新增方法详解

日期:2019-08-13点击:570

1、compute

default V compute(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)
Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
尝试通过Lambda表达式重新计算给定KEY的映射值并更新MAP(值为null则删除KEY,否则重新写入)。

 Map<String, String> tMap = new HashMap<String, String>() { { put("A", "AAA"); put("B", "BBB"); } }; tMap.compute("A", (k, v) -> v == null ? "AAA" : v.concat("AAA"));//KEY存在VALUE不为空且Lambda计算结果不为空,更新KEY System.out.println(tMap); tMap.compute("B", (k, v) -> v == null ? "BBB" : null);//KEY存在VALUE不为空但Lambda计算结果为空,删除KEY System.out.println(tMap); tMap.compute("C", (k, v) -> v == null ? "CCC" : v.concat("CCC"));//KEY不存在但Lambda计算结果不为空,新增KEY System.out.println(tMap);

image

2、computeIfAbsent

default V computeIfAbsent(K key,Function<? super K,? extends V> mappingFunction)

If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.

如果给定的KEY为关联VALUE或关联到null,则尝试通过给定的Lambda函数计算其值并写入MAP(值为null则不写入)。

Map<String,String> map = new HashMap<>(); map.computeIfAbsent("A",k -> null); System.out.println(map); map.computeIfAbsent("B",k -> "BBB"); System.out.println(map);

image

3、computeIfPresent

default V computeIfPresent(K key,BiFunction<? super K,? super V,? extends V> remappingFunction)

If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
如果给定KEY存在映射值且非null,尝试通过Lambda表达式计算新值并更新MAP

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.
如果Lambda计算结果为null,则删除KEY。如果Lambda计算发生异常,则原映射关系不变。

Map<String, String> tMap = new HashMap<String, String>() { { put("A", "AAA"); put("B", "BBB"); } }; tMap.computeIfPresent("A", (k, v) -> v == null ? "AAA" : v.concat("AAA"));//Lambda计算结果不为空,更新KEY System.out.println(tMap); tMap.computeIfPresent("B", (k, v) -> v == null ? "BBB" : null);//Lambda计算结果为空,删除KEY System.out.println(tMap);

image

原文链接:https://yq.aliyun.com/articles/714329
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章