1.1. 通过key得到value
//得到所有的key值 Set<String> keySet = map.keySet(); //根据key值得到value值 for (String key : keySet) { System.out.println(key+":"+map.get(key)); } |
1.2. 通过entry得到key和value
//得到所有的entry Set<Entry<String, String>> entrySet = //从entry中得到key和value值 for (Entry<String, String> entry : entrySet) { System.out.println(entry.getKey()+":"+entry.getValue()); } |
1.3. 完整示例代码
MapTest.java |
package map; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.junit.BeforeClass; import org.junit.Test; publicclass MapTest { private Map map; @BeforeClass publicvoid init(){ map = new HashMap<String, String>(); map.put("1", "Morris"); map.put("2", "Jack"); map.put("3", "Bob"); map.put("4", "Tom"); } @Test publicvoid traversal1(){ //得到所有的key值 Set<String> keySet = map.keySet(); //根据key值得到value值 for (String key : keySet) { System.out.println(key+":"+map.get(key)); } } @Test publicvoid traversal2(){ //得到所有的entry Set<Entry<String, String>> entrySet = map.entrySet(); //从entry中得到key和value值 for (Entry<String, String> entry : entrySet) { System.out.println(entry.getKey()+":"+entry.getValue()); } } } |
时间: 2024-10-07 22:01:35