Map循环4种方式
2018-07-13 16:52:57 SecondDream_1017 阅读数 1236
遍历方式:
-
Map<String,String> map = new HashMap<String, String>();
-
map.put("1","java");
-
map.put("2","c");
-
map.put("3","go");
1、取值遍历
-
for(String key:map.keySet()){
-
System.out.println("key="+key+"and value=" +map.get(key));
-
}
2、Iterator遍历
-
Iterator<Map.Entry<String,String>> it = map.entrySet().iterator();
-
while(it.hasNext()){
-
Map.Entry<String,String> entry=it.next();
-
System.out.println("key=" +entry.getKey() +" and value="+entry.getValue());
-
}
3、遍历所有的Value值
该方式取得不了key值,直接遍历map中存放的value值。
-
for(String v:map.values()){
-
System.out.println("value= "+ v);
-
}
4、使用entrySet遍历
-
for(Map.Entry<String,String > entry:map.entrySet()){
-
System.out.println("key=" +entry.getKey() +" and value="+entry.getValue());
-
}
注意:大量数据时使用该方式效率更高。
public class TestMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "a1");
map.put("2", "a2");
map.put("3", "a3");
map.put("4", "a4");
// TraversingMap1(map);
// traversingMap2(map);
// traversingMap3(map);
traversingMap4(map);
}
/**
* 遍历方式1:加强for循环,遍历map
*/
public static void TraversingMap1(Map<String, String> map) {
for (Object key : map.keySet()) {
System.out.println("key:" + key + "--value:" + map.get(key));
}
}
/**
* @description: 用iterator,遍历map
*/
public static void traversingMap2(Map<String, String> map) {
for(Iterator<Map.Entry<String, String>> ite = map.entrySet().iterator(); ite.hasNext();) {
Map.Entry<String, String> next = ite.next();
System.out.println("key:" + next.getKey() + "--value:" + next.getValue());
}
}
/**
* @description: 遍历所有的Value值
该方式取得不了key值,直接遍历map中存放的value值。
*/
public static void traversingMap3(Map<String,String> map){
for(String o : map.values()){
System.out.println("map:"+o);
}
}
/**
* @description: 用entryset()遍历
*/
public static void traversingMap4(Map<String,String> map){
for(Map.Entry<String,String> entry: map.entrySet()) {
System.out.println("key:"+entry.getKey()+"--value:"+entry.getValue());
}
}