当前位置 : 主页 > 编程语言 > java >

HashMap集合的3种迭代方式

来源:互联网 收集:自由互联 发布时间:2022-10-14
package teat; import java.util.*; import java.util.Map.Entry; /** * @author linjitai */ public class ThreeIterator { public static void main(String[] args) { MapString, String map = new HashMap(); map.put("001", "宝马"); map.put("002", "奔
package teat;


import java.util.*;

import java.util.Map.Entry;


/**

* @author linjitai

*/

public class ThreeIterator {

public static void main(String[] args) {

Map<String, String> 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<String, String> map) {

for (Entry<String, String> 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<String, String> 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<String, String> map) {

Iterator<String> 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 = 奥迪*/
上一篇:类与类之间的关系
下一篇:没有了
网友评论