Java中的map遍歷有多種方法,從最早的Iterator,到java5支持的foreach,再到java8 Lambda,讓我們一起來看下Java中Map集合的兩種遍歷方式!
關于遍歷Map集合的幾種方式:
1.獲取Map集合的所有key,通過遍歷所有的key獲取Map中對應的所有value。
java的map集合、用到的方法:Map中的keySet()方法, Set中的get(K key)方法。
2.把Map集合轉換成Set集合,通過遍歷Set集合獲取key和value。
用到的方法:Map中的entrySet()方法,Map.Entry類中的getKey(),getValue()方法。
第2種方法比第1種方法效率要高,因為第1種獲取key之后還要去Map集合中去找value,而第2種方法是直接從轉成的Set集合中獲取到key和value。
測試代碼:
import java.util.*;public class Test02 {public static void main(String[] args) {// 先創建Map集合Map<Integer, String> hashMap = new HashMap<>();// 添加幾個鍵值對hashMap.put(1, "張三");hashMap.put(2, "李四");hashMap.put(3, "王五");hashMap.put(4, "趙六");System.out.println(hashMap.size()); // 4// 1.獲取Map集合的所有key,通過遍歷所有的key獲取Map中對應的所有value。// 先獲取Map中所有的key,得到一個Set集合Set<Integer> keys = hashMap.keySet();// 再遍歷保存所有key的Set集合,Set集合沒有下標,遍歷集合只有2種方式// 迭代器遍歷Set集合Iterator<Integer> it = keys.iterator();while (it.hasNext()) {Integer key = it.next();String value = hashMap.get(key);System.out.print(key + "-" + value + " "); // 1-張三 2-李四 3-王五 4-趙六}System.out.println();// foreach遍歷Set集合for (Integer i : keys) {Integer key = i;String value = hashMap.get(key);System.out.print(key + "-" + value + " "); // 1-張三 2-李四 3-王五 4-趙六}System.out.println();//2.把Map集合轉換成Set集合,通過遍歷Set集合獲取key和value。// Map集合轉成Set集合Set<Map.Entry<Integer, String>> mapToSet = hashMap.entrySet();// 迭代器遍歷Set集合Iterator<Map.Entry<Integer, String>> it1 = mapToSet.iterator();while (it1.hasNext()) {Map.Entry<Integer, String> mn = it1.next();Integer key = mn.getKey();String value = mn.getValue();System.out.print(key + "-" + value + " "); // 1-張三 2-李四 3-王五 4-趙六}System.out.println();// foreach遍歷Set集合for (Map.Entry<Integer, String> mn : mapToSet) {Integer key = mn.getKey();String value = mn.getValue();System.out.print(key + "-" + value + " "); // 1-張三 2-李四 3-王五 4-趙六}System.out.println();}
}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态