1. 程式人生 > >HashMap遍歷的三種方式

HashMap遍歷的三種方式

1.遍歷HashMap的鍵值對
(1)通過entrySet()獲取HashMap的"鍵值對"的Set集合(於Set中無序排放)。
(2)通過迭代方法遍歷集合,再利用getKey(),getValue()方法獲取相應鍵,值。
1.1例項程式碼

package hashmap;
//Map集合獲取元素的三種常見方法 keyset(),values(),entrySet()
import java.util.*;
public class ValuesTest {
		public static void main(String[] args) {
		Map<String, Integer>
map = new HashMap<String, Integer>(); //構建鍵值對為<String, Integer>的Map集合 map.put("你好", 1); //// 將“key-value”新增到HashMap中 map.put("天天", 2); map.put("價格", 10); map.put("悟空", 5); map.put("活著", 7); // //entrySet()方法 Set<Map.Entry<String, Integer>> entrySet = map.entrySet(); //獲取map集合的所有“對映”的Set集合,這裡規範每個對映的型別為Map.Entry<K,V>(於Set集合中無序存放)
Iterator<Map.Entry<String, Integer>> iterator2 = entrySet.iterator(); //獲取entrySet集合的迭代器,Map.Entry<k,V>為迭代元素的型別 for(Map.Entry<String, Integer> item : entrySet) { String key = item.getKey(); Integer value = item.getValue(); System.out.println("key:" + key + "-->value:"
+ value); } } }

1.2 執行結果
在這裡插入圖片描述
2.遍歷HashMap的鍵
通過keySet()方法,獲取HashMap的所有鍵的Set集合,通過迭代取出所有key,再利用get()方法獲取value。
2.1例項程式碼

package hashmap;
//Map集合獲取元素的三種常見方法 keyset(),values(),entrySet()
import java.util.*;
public class ValuesTest {
		public static void main(String[] args) {
		Map<String, Integer> map = new HashMap<String, Integer>(); //構建鍵值對為<String, Integer>的Map集合
		map.put("你好", 1); //// 將“key-value”新增到HashMap中
		map.put("天天", 2);
		map.put("價格", 10);
		map.put("悟空", 5);
		map.put("活著", 7);	
		//keySet()方法
		Set<String> keySet = map.keySet(); //獲取map集合所有鍵的Set()集合(於集合中無序存放)
		Iterator<String> iterator = keySet.iterator(); //獲取keySet集合的迭代器
		while(iterator.hasNext()) {
			String key = iterator.next(); //獲取key值
			Integer value = map.get(key); //通過get()方法獲取對應value
			System.out.println("key:" + key + "-->value:" + value);
		}
	}
}

2.2 執行結果
在這裡插入圖片描述
3.遍歷HashMap的值
通過values()方法獲取HashMap集合的所有value的Collection集合(於集合中無序存放)。
3.1程式碼例項

package hashmap;
//Map集合獲取元素的三種常見方法 keyset(),values(),entrySet()
import java.util.*;
public class ValuesTest {
		public static void main(String[] args) {
		Map<String, Integer> map = new HashMap<String, Integer>(); //構建鍵值對為<String, Integer>的Map集合
		map.put("你好", 1); //// 將“key-value”新增到HashMap中
		map.put("天天", 2);
		map.put("價格", 10);
		map.put("悟空", 5);
		map.put("活著", 7);
		
		
		//values方法 遍歷HashMap的values
		Collection<Integer> collection = map.values(); //獲取map集合的所有value的Collection(於集合中無序存放)
		System.out.println(collection);
		Iterator iterator = collection.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}		
		
	}
}

3.2 執行結果
在這裡插入圖片描述