package com.study.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @author dl_zy
* @describe map的四种遍历方式
*/
public class forMap {
Map<String,String> map = new HashMap<String, String>();
public forMap () {
map.put("1","java");
map.put("2","c#");
map.put("3","php");
}
// 第一种:取值遍历
public void getValueFirst () {
for (String key : map.keySet()) {
System.out.println("key="+key+"; value=" +map.get(key));
}
}
// 第二种:Iterator遍历
public void getValueSecond () {
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()+";value="+entry.getValue());
}
}
// 第三种:遍历所有的Value值
// 注意:该方式取得不了key值,直接遍历map中存放的value值。
public void getValueThird () {
for (String v : map.values()) {
System.out.println("value= "+ v);
}
}
// 第四种:使用entrySet遍历
// 注意: 大量数据时使用此方式时效率高
public void getValueForth () {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key=" +entry.getKey() +" and value="+entry.getValue());
}
}
public static void main(String[] args) {
new forMap().getValueFirst();
new forMap().getValueSecond();
new forMap().getValueThird();
new forMap().getValueForth();
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @author dl_zy
* @describe map的四种遍历方式
*/
public class forMap {
Map<String,String> map = new HashMap<String, String>();
public forMap () {
map.put("1","java");
map.put("2","c#");
map.put("3","php");
}
// 第一种:取值遍历
public void getValueFirst () {
for (String key : map.keySet()) {
System.out.println("key="+key+"; value=" +map.get(key));
}
}
// 第二种:Iterator遍历
public void getValueSecond () {
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()+";value="+entry.getValue());
}
}
// 第三种:遍历所有的Value值
// 注意:该方式取得不了key值,直接遍历map中存放的value值。
public void getValueThird () {
for (String v : map.values()) {
System.out.println("value= "+ v);
}
}
// 第四种:使用entrySet遍历
// 注意: 大量数据时使用此方式时效率高
public void getValueForth () {
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key=" +entry.getKey() +" and value="+entry.getValue());
}
}
public static void main(String[] args) {
new forMap().getValueFirst();
new forMap().getValueSecond();
new forMap().getValueThird();
new forMap().getValueForth();
}
}