/**
* MAP遍历
*
* @author: NPF
* @date: 2018/2/27.
*/
public class MapUtil {
public static void main(String[] args) {
Map<String, Integer> tempMap = new HashMap<>();
tempMap.put("a", 111);
tempMap.put("b", 222);
tempMap.put("c", 333);
each1(tempMap);
each2(tempMap);
each3(tempMap);
each4(tempMap);
eachMapList();
}
/**
* JDK1.4
* Map entrySet() 遍历
*
* @param tempMap
*/
private static void each1(Map<String, Integer> tempMap) {
Iterator it = tempMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
Integer value = (Integer) entry.getValue();
System.out.println("key=" + key + " value=" + value);
}
}
/**
* JDK1.5中,应用新特性For-Each循环
*
* @param tempMap
*/
private static void each2(Map<String, Integer> tempMap) {
for (Map.Entry<String, Integer> entry : tempMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("key=" + key + " value=" + value);
}
}
/**
* Map keySet() 遍历
*
* @param tempMap
*/
private static void each3(Map<String, Integer> tempMap) {
/**
* 循环获取key,通过key再获取value
*/
for (Iterator i = tempMap.keySet().iterator(); i.hasNext(); ) {
String key = (String) i.next();
Integer value = tempMap.get(key);
System.out.println("key=" + key + " value=" + value);
}
/**
* 循环获取value
*/
for (Iterator i = tempMap.values().iterator(); i.hasNext(); ) {
Integer value = (Integer) i.next();
System.out.println("value=" + value);
}
}
/**
* Map keySet()遍历
*
* @param tempMap
*/
private static void each4(Map<String, Integer> tempMap) {
for (String key : tempMap.keySet()) {
Integer value = tempMap.get(key);
System.out.println("key=" + key + " value=" + value);
}
}
/**
* 遍历Map <String, ArrayList> map = new HashMap <>();
*/
private static void eachMapList() {
/**
* 方式一
*/
Map<String, ArrayList<String>> map1 = new HashMap<>();
Set<String> keys = map1.keySet();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
ArrayList<String> arrayList = map1.get(key);
for (String value : arrayList) {
System.out.println(key + "==方式一==" + value);
}
}
/**
* 方式二
*/
Map<String, List<String>> map2 = new HashMap<>();
for (Map.Entry entry : map2.entrySet()) {
String key = entry.getKey().toString();
List<String> list = (List) entry.getValue();
for (String value : list) {
System.out.println(key + "==方式二==" + value);
}
}
}}
网友评论