可以用3种方法遍历- import java.util.*;
- public class Test {
- public static void main(String[] args) {
- Map<String,Integer> map =new HashMap<String,Integer>();
- map.put("一", 1);
- map.put("二", 2);
-
- workByCollection(map);
- workByKeySet(map);
- workByEntry(map);
- }
- //常规的一种遍历值的方法
- public static void workByCollection(Map<String, Integer> map){
- Collection<Integer> c = map.values();
- for (Iterator<Integer> it = c.iterator(); it.hasNext();) {
- System.out.println(it.next());
- }
- }
-
- //利用keyset进行遍历,它的优点在于可以根据你所想要的key值得到你想要的 values
- public static void workByKeySet(Map<String, Integer> map) {
- Set<String> key = map.keySet();
- for (Iterator<String> it = key.iterator(); it.hasNext();) {
- String s = (String) it.next();
- System.out.println(map.get(s));
- }
- }
-
- //通过Map嵌套的接口Map.Entry<K,V>,返回此映射中包含的映射关系的 Set 视图
- public static void workByEntry(Map<String, Integer> map) {
- Set<Map.Entry<String, Integer>> set = map.entrySet();
- for (Iterator<Map.Entry<String, Integer>> it = set.iterator(); it.hasNext();) {
- Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) it.next();
- System.out.println(entry.getKey() + "--->" + entry.getValue());
- }
- }
- }
-
复制代码 第三种比较强大也比较常用,楼上已经说啦 |