Java基础之Java8中Map

什么是Map

map属于java中的顶级接口之一,区别于list,map是键值对的形式存在。有个大神举例的好,map就相当于夫妻,而list相当于单身狗。


类图


接口中的方法解析,以hashMap为例:

size

获取键值对数量

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
System.out.println(map.size());

isEmpty

键值对是否不存在

HashMap<String,Object> map = new HashMap<>();
System.out.println(map.isEmpty());

结果

true


 containsKey/containsValue

map中是否存在指定的key/value

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
System.out.println(map.containsKey("1"));
System.out.println(map.containsValue("123"));

结果

false
true


get

通过key获取value,查询不到返回null

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
System.out.println(map.get("a"));

 结果

123


 put

写入键值对,但key不能重复,如果重复会覆盖前一个元素,判断依据好像是hasCode

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
map.put("a","444");
System.out.println(map.size());

结果

1


 remove

根据key删除对应的元素,如果不存在则不删除也不报错。

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
map.put("6","444");
map.remove("6");
System.out.println(map.size());
//如果key,value存在且对应则删除,否者不删除
map.remove("a","123");
System.out.println(map.size());

putAll

加入其它map

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
Map maps = new HashMap();
maps.put("6","444");
map.putAll(maps);
System.out.println(map);

结果

{a=123, 6=444}


clear

清除所有键值对

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
map.clear();
System.out.println(map);

 结果

{}


keySet

返回此地图中包含的键的set视图。

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
System.out.println(map.keySet());

结果

[a] 


values

返回此地图中包含的值的Collection视图

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
map.put("7","444");
System.out.println(map.values());

结果

[123, 444]


entrySet

返回此地图中包含的映射的Set视图。

HashMap<String,Object> map = new HashMap<>();
map.put("a","123");
map.put("7","444");
System.out.println(map.entrySet());

 结果

 [a=123, 7=444]


equals

相等判断


hashCode

获取hashCode值


getOrDefault

根据键值获取值,如果值不存在,则返回默认值

HashMap<String,Object> map = new HashMap<>();
map.put("7","444");
System.out.println(map.getOrDefault("7","444"));
System.out.println(map.getOrDefault("6","4544"));

结果

444
4544


forEach

循环

Map<Object, Object> map = new HashMap<>();
map.put("name", "xiang");
map.put("gender", "男");
map.put("phone", "18877458888");
map.put(null, null);
//1.Map的迭代
// 通用的Map迭代方式
System.out.println("==============Map的迭代======================");
for (Map.Entry<Object, Object> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("====================================");
// JDK8的迭代方式
map.forEach((key, value) -> {
    System.out.println(key + ":" + value);
});

putIfAbsent

如果值不存在,则写入填充值

HashMap<String,Object> map = new HashMap<>();
map.put("7",null);
map.putIfAbsent("7","999");
System.out.println(map);

 结果

{7=999}


replace/replaceAll

置换

HashMap<String,Object> map = new HashMap<>();
map.put("7","999");
map.put("wudi","999");
map.replace("7","999","666");
System.out.println(map);
map.replace("7","333");
System.out.println(map);
//批量替换,可以根据key与value的映射确定值
map.replaceAll((x,y)->{
    if(x.length()>3){
        return y+"aa";
    }else{
        return "123";
    }
});
System.out.println(map);

结果

{wudi=999, 7=666}
{wudi=999, 7=333}
{wudi=999aa, 7=123}


 computeIfAbsent

如果指定的键尚未与值相关联(或映射到 null ),则尝试使用给定的映射函数计算其值,并将其输入到此映射中,除非 null 。

// java8之前。从map中根据key获取value操作可能会有下面的操作
Object key = map.get("key");
if (key == null) {
    key = new Object();
    map.put("key", key);
}
System.out.println(key);

// java8之后。上面的操作可以简化为一行,若key对应的value为空,会将第二个参数的返回值存入并返回
Object key2 = map.computeIfAbsent("key", k -> new Object());
System.out.println(key2);

computeIfPresent

参数说明:

  • key - 键
  • remappingFunction - 重新映射函数,用于重新计算值

返回值:

如果 key 对应的 value 不存在,则返回空指针,如果存在,则返回通过 remappingFunction 重新计算后的值。

// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();

// 往HashMap中添加映射关系
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);

// 重新计算鞋加上10%的增值税后的价值
int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);
System.out.println("Price of Shoes after VAT: " + shoesPrice);

// 输出更新后的HashMap
System.out.println("Updated HashMap: " + prices);

结果

HashMap: {Pant=150, Bag=300, Shoes=200}
Price of Shoes after VAT: 220
Updated HashMap: {Pant=150, Bag=300, Shoes=220}


compute

根据key,value 映射出value

//统计元素出现的个数
String str = "hello java, i am vary happy! nice to meet you";

// jdk1.8之前的写法
HashMap<Character, Integer> result1 = new HashMap<>(32);
for (int i = 0; i < str.length(); i++) {
    char curChar = str.charAt(i);

    result1.compute(curChar,(x,y)->{
        Integer curVal = result1.get(curChar);
        if (curVal == null) {
            curVal = 1;
        } else {
            curVal += 1;
        }
        return curVal;
    });
}

System.out.println(result1);

结果

{ =9, !=1, a=5, c=1, e=4, h=2, i=2, j=1, ,=1, l=2, m=2, n=1, o=3, p=2, r=1, t=2, u=1, v=2, y=3}


merge

使用场景较多。

入参3个,(key,value1,函数)

  1. 如果key查询map存在,则通过key查询的value与value1执行函数
  2. 如果key不存在,则返回put(key,value1)
Map<String, Integer> map = new HashMap<>();
map.put("name", 1);
map.merge("name", 2, (oldValue, newValue) -> oldValue + newValue);
map.merge("count", 1, (oldValue, newValue) -> oldValue + newValue);
System.out.println(map);

结果

{count=1, name=3}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值