HashMap集合的3种迭代方式

package teat;

import java.util.*;
import java.util.Map.Entry;

/**
 * @author linjitai
 */
public class ThreeIterator {
public static void main(String[] args) {
Map map = new HashMap<>();
map.put("001", "宝马");
map.put("002", "奔驰");
map.put("003", "奥迪");
firstIterator(map);
System.out.println("===");
twoIterator(map);
System.out.println("===");
threeItertor(map);
}
/**
* entry
* @param map
* @return
*/
public static void firstIterator(Map map) {
for (Entry entry : map.entrySet()) {
String keys = entry.getKey();
String values = entry.getValue();
System.out.println("key = "+ keys + ";value = "+ values);
}
}
/**
* keySet
* @param map
*/
public static void twoIterator(Map map) {
for (String keys : map.keySet()) {
String values = map.get(keys);
System.out.println("key = "+ keys + ";value = "+ values);
}
}
/**

* @param map
*/
public static void threeItertor(Map map) {
Iterator keys = map.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
String value = map.get(key);
System.out.println("key = "+ key + ";value = "+ value);
}
}
}
/**

Output

key = 001;value = 宝马
key = 002;value = 奔驰
key = 003;value = 奥迪
===
key = 001;value = 宝马
key = 002;value = 奔驰
key = 003;value = 奥迪
===
key = 001;value = 宝马
key = 002;value = 奔驰
key = 003;value = 奥迪

*/

你可能感兴趣的:(JavaSE,集合)