public class M {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
//通过通过遍历entrySet()方法得到的Set
for (Map.Entry<String, String> m : map.entrySet()) {
System.out.println("KEY:" + m.getKey() + "VALUE:" + m.getValue());
}
//通过迭代器Iterator遍历
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("KEY:" + entry.getKey() + "VALUE:" + entry.getValue());
}
//遍历keySet()方法获得的Set(通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作;)
for (String key : map.keySet()) {
System.out.println("KEY:" + key + "VALUE:" + map.get(key));
}
//使用keySet()和values(),这种方法用于单独只获取key或者value很好
for (String key:map.keySet()){
System.out.println("KEY:" + key);
}
for (String value:map.values()){
System.out.println("VALUE:" + value);
}
}
}
Java中Map的遍历方法
最新推荐文章于 2024-04-18 05:41:33 发布