HashMap集合类 5种最佳遍历方式
1. 使用 Iterator 遍历 HashMap EntrySet
2. 使用 Iterator 遍历 HashMap KeySet
3. 使用 For-each 循环迭代 HashMap
4. 使用 Lambda 表达式遍历 HashMap
5. 使用 Stream API 遍历 HashMap
显示例子:
1. 使用 Iterator 遍历 HashMap EntrySet
package com.jia.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapDemo { public static void main(String[] args) { Map<Integer,String> map = new HashMap<>(); map.put(1,"java"); map.put(2,"c"); map.put(3,"c++"); map.put(4,"c#"); map.put(5,"spring"); Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator(); while (iterator.hasNext()){ Map.Entry<Integer, String> entry = iterator.next(); System.out.println(entry.getKey() + ":" + entry.getValue()); } } }
Output:
1:java 2:c 3:c++ 4:c# 5:spring Process finished with exit code 0
2. 使用 Iterator 遍历 HashMap KeySet
package com.jia.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapDemo02 { public static void main(String[] args) { Map<Integer,String> map = new HashMap<>(); map.put(1,"java"); map.put(2,"c"); map.put(3,"c++"); map.put(4,"c#"); map.put(5,"spring"); Iterator<Integer> iterator = map.keySet().iterator(); while (iterator.hasNext()){ Integer key = iterator.next(); System.out.println(key); System.out.println(map.get(key)); } } }
Output:
1 java 2 c 3 c++ 4 c# 5 spring Process finished with exit code 0
3. 使用 For-each 循环遍历 HashMap
package com.jia.map; import java.util.HashMap; import java.util.Map; public class HashMapDemo03 { public static void main(String[] args) { Map<Integer,String> map = new HashMap<>(); map.put(1,"java"); map.put(2,"c"); map.put(3,"c++"); map.put(4,"c#"); map.put(5,"spring"); for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } }
Output:
1:java 2:c 3:c++ 4:c# 5:spring Process finished with exit code 0
4. 使用 Lambda 表达式遍历 HashMap(推荐!!!)
package com.jia.map; import java.util.HashMap; import java.util.Map; public class HashMapDemo04 { public static void main(String[] args) { Map<Integer,String> map = new HashMap<>(); map.put(1,"java"); map.put(2,"c"); map.put(3,"c++"); map.put(4,"c#"); map.put(5,"spring"); map.forEach((key,value) ->{ System.out.println(key + ":" + value); }); } }
Output:
1:java 2:c 3:c++ 4:c# 5:spring Process finished with exit code 0
5. 使用 Stream API 遍历 HashMap(推荐!!!)
package com.jia.map; import java.util.HashMap; import java.util.Map; public class HashMapDemo05 { public static void main(String[] args) { Map<Integer,String> map = new HashMap<>(); map.put(1,"java"); map.put(2,"c"); map.put(3,"c++"); map.put(4,"c#"); map.put(5,"spring"); map.entrySet().stream().forEach((entry) ->{ System.out.println(entry.getKey() + ":" + entry.getValue()); }); } }
Output:
1:java 2:c 3:c++ 4:c# 5:spring Process finished with exit code 0