首页 > 编程 > Java > 正文

java8 特性例子 Map 新增方法

2019-11-08 19:49:18
字体:
来源:转载
供稿:网友

public class MapTest {	public static void main(String[] args) {		Map<Integer, String> map = new HashMap<>();		for (int i = 0; i < 10; i++) {			map.putIfAbsent(i, "val" + i);		}		map.forEach((id, val) -> System.out.PRintln(val));		map.computeIfPresent(3, (num, val) -> val + num);		System.out.println(map.get(3)); // val33		map.computeIfPresent(9, (num, val) -> null);		System.out.println(map.containsKey(9)); // false		map.computeIfAbsent(23, num -> "val" + num * 2);		System.out.println(map.containsKey(23)); // true		System.out.println(map.get(23)); // val46		// 已经存在就,不存在才替换		map.computeIfAbsent(3, num -> "bam");		System.out.println(map.get(3)); // val33		// key 和value都匹配时才删除		map.remove(3, "val3");		map.get(3); // val33		map.remove(3, "val33");		map.get(3); // null		map.getOrDefault(42, "not found"); // not found		// 如果原来不存在,就设置成指定的value		map.merge(9, "val9", (value, newValue) -> value.concat(newValue));		System.out.println(map.get(9)); // val9		// 如果key存在,则把value设置成重新计算后的结果		map.merge(9, "val9", (value, newValue) -> value.concat(newValue));		System.out.println(map.get(9)); // val9val9	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表