New method for map in Java 8
•
Java
public class MapTest {
public static void main(String[] args) {
Map map = new HashMap();
// 成对放入多个key-value对
map.put("Java入门教程",10);
map.put("C语言入门教程",20);
map.put("Python基础教程",30);
// 尝试替换key为”Go语言入门教程”的 value,由于原 Map 中没有对应的 key
// 因此Map没有改变,不会添加新的key-value对
map.replace("Go语言入门教程",40);
System.out.println(map);
// 使用原value与传入参数计算出来的结果覆盖原有的value
map.merge("C语言入门教程",25,(oldVal,param) -> (Integer) oldVal + (Integer) param);
System.out.println(map);
// 当key为"Java"对应的value为null (或不存在)时,使用计算的结果作为新value
map.computeIfAbsent("Java",(key) -> ((String) key).length());
System.out.println(map); // map 中添加了 Java=4 这组 key-value 对
// 当key为"Java"对应的value存在时,使用计算的结果作为新value
map.computeIfPresent("Java",(key,value) -> (Integer) value * (Integer) value);
System.out.println(map); // map 中 Java=4 变成 Java=16
}
}
{Java introductory tutorial = 10, python basic tutorial = 30, C language introductory tutorial = 20} {Java introductory tutorial = 10, C language introductory tutorial = 45} {Java = 4, Java introductory tutorial = 10, C language introductory tutorial = 45} {Java = 16, C language introductory tutorial = 45}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
