Java中HashMap的常用操作
生活随笔
收集整理的這篇文章主要介紹了
Java中HashMap的常用操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Java中HashMap的常用操作
當在hashmap中put的key在之前已經存過,則不會重復存儲,會覆蓋之前key對應的value
1.containsKey(Object key)方法,返回值為boolean,用于判斷當前hashmap中是否包含key對應的key-value
2.containsValue(Object value)方法,返回值為boolean,用于判斷當前hashmap中是否包含value對應的key-value
3.遍歷hashmap的兩種方式:
(1)利用haspmap.entrySet().iterator():利用迭代器,從Entry中取出鍵、取出值,推薦使用這種方式進行遍歷,效率較高
Iterator<Entry<Integer, Integer>> iterator = hashMap.entrySet().iterator();while (iterator.hasNext()) {Entry<Integer, Integer> entry = iterator.next();Integer key = entry.getKey();Integer value = entry.getValue();System.out.print(key + "--->" + value);System.out.println();} (2)利用hashmap.keySet().iterator():利用鍵的迭代器,每次取出一個鍵,再根據鍵,從hashmap中取出值,這種方式的效率不高,不推薦使用
完整源碼如下:
import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry;public class HashMapTest {public static void main(String args[]) {HashMap<String, String> hm = new HashMap<String, String>();HashMap<Integer, String> hm1 = new HashMap<Integer, String>();hm.put("a1", "lhj");hm.put("a2", "ldj");hm.put("a3", "zyl");hm.put("a4", "wpang");hm1.put(1, "cjh");hm1.put(2, "czy");/** 遍歷HashMap很重要的一個方法 , 利用haspmap.entrySet().iterator():* 利用迭代器,從Entry中取出鍵、取出值,推薦使用這種方式進行遍歷,效率較高*/ Iterator<Entry<String, String>> iterator = hm.entrySet().iterator();while (iterator.hasNext()) {Entry<String, String> entry = iterator.next();String key = entry.getKey();String value = entry.getValue();System.out.println(key + " " + value);}/** 利用hashmap.keySet().iterator():利用鍵的迭代器,每次取出一個鍵,* 再根據鍵,從hashmap中取出值,這種方式的效率不高,不推薦使用*/Iterator<String> it = hm.keySet().iterator();while(it.hasNext()) {String a = it.next();System.out.print(a+" ");System.out.print(hm.get(a));System.out.println();}Iterator<Integer> it1 = hm1.keySet().iterator();while(it1.hasNext()) {int a = it1.next();System.out.print(a+" ");System.out.print(hm1.get(a));System.out.println();}System.out.println("通過鍵值來獲取value:"+hm.get("a1"));System.out.println("判斷是否含有此key:"+hm.containsKey("a5"));System.out.println("長度為:"+hm.size());System.out.println("map是否為null:"+hm.isEmpty());System.out.println("移除指定的key:"+hm.remove("a1"));hm.clear();//清空HashMap}}參考博文:https://blog.csdn.net/u013398759/article/details/77679632總結
以上是生活随笔為你收集整理的Java中HashMap的常用操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java基础————理解Integer对
- 下一篇: Linux进阶之路————crond定时