当前位置:   article > 正文

【Java】散列映射(HashMap)七条必备知识点

散列映射

1、若映射中没有存储与给定键对应的信息,get方法会返回null
如果希望返回你设定的默认值,使用getOrDefault方法。

//situation 1
var id = "00000000";
Employee e = staff.get(id);
//如果id不存在,不会报错,e == null

//situation 2
int score = scores.getOrDefault(id, 0);
//如果id不存在,score == 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

2、put方法有返回值,它会返回与这个键相关联的上一个值。

var sores = new HashMap<String, Integer>();
scores.put("Bob", 99);
int old = scores.put("Bob", 100);
//old == 99
  • 1
  • 2
  • 3
  • 4

3、迭代处理映射中的键与值

  1. 使用 forEach + lambda表达式
scores.forEach((k, v) ->
   {
      ...
   }
);
  • 1
  • 2
  • 3
  • 4
  • 5
  1. 使用entrySet
for(var entry : scores.entrySet())
{
   System.out.println("key = " + entry.getKey());
   System.out.println("value = " + entry.getValue());
}
  • 1
  • 2
  • 3
  • 4
  • 5

4、remove(key)方法会删除一个键值对。

5、HashMap具有三个构造器,允许设置初始容量与装填因子(默认为0.75),一旦装填因子超过设置值,会再散列至一个更大的散列表中。

6、试想你需要通过映射统计一个单词在文件中出现的频度。
这样写是错误的

counts.put(word, counts.get(word) + 1);
  • 1

因为当第一次出现一个单词时,get函数返回null,因此会爆发NullPointerException异常。
以下有三种改写方式:

//Method 1
counts.put(word,counts.getOrDefault(word, 0) + 1);
//Method 2
counts.putIfAbsent(word, 0);
count.put(word, counts.get(word) + 1);
//Method 3
counts.merge(word, 1, Integer::sum);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

merge方法的作用原理如下:
若key(word)相关联的值不是null,则将函数(Integer::sum)应用到原先相关联的值与函数中的数值(1),若结果非null,将key与结果相关联;若结果为null,将键删除。
若key原先没有关联值,将key与函数中的数值相关联。
这样就可以快速更新映射条目了。

7、映射视图

// 键集:
Set<String> keys = staff.keySet();
for(String key : keys)
{
   ...
}
//值集合:
for(Empolyee employee : staff.values())
{
   ...
}
//键值对集:
for(Map.Entry<String, Employee> entry : staff.entrySet())
//或写成 var entry : staff.entrySet()
{
   String k = entry.getKey();
   Employee v = entry.getValue();
   ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

注意

  1. 映射视图(键集、值集合、键值对集)都是实现了Collection接口或者某个子接口的对象。
  2. 键值对集中的元素(entry)是实现了Map.Entry接口的类的对象。
  3. keySet既不是HashSet也不是TreeSet,而是另外某个实现了Set接口的类的对象。由于Set接口扩展于Collection接口,因此keySet可以像任何集合一样使用。
  4. 对keySet中的元素调用remove方法会从映射中删除键和与之相联的值。
  5. 禁止向键集视图或键值对集中添加元素,试图调用add方法会爆发UnsupportedOperationException异常。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/960035
推荐阅读
相关标签
  

闽ICP备14008679号