- package javaCode0507;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class testMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("key_1", "value_1");
map.put("key_2", "value_2");
getValueFromMap1(map);
getValueFromMap2(map);
getValueFromMap3(map);
getValueFromMap4(map);
}
public static void getValueFromMap1( Map<String, String> map){
System.out.println("-----------------------getValueFromMap1----------------------------------");
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
//如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。
//该方法比entrySet遍历在性能上稍好(快了10%),而且代码更加干净。
public static void getValueFromMap3( Map<String, String> map){
System.out.println("-----------------------getValueFromMap3----------------------------------");
//遍历map中的键
for (String key : map.keySet()) {
System.out.println("Key = " + key);
}
//遍历map中的值
for (String value : map.values()) {
System.out.println("Value = " + value);
}
}
public static void getValueFromMap2( Map map){
System.out.println("-----------------------getValueFromMap2----------------------------------");
Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Entry<String, String> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
//无泛型
public static void getValueFromMap4( Map map){
System.out.println("-----------------------getValueFromMap4----------------------------------");
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
}
public static void getValueFromMap5( Map map){
System.out.println("-----------------------getValueFromMap5----------------------------------");
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
}
}
遍历map的几种方法
最新推荐文章于 2023-11-11 21:07:26 发布