Java中如何遍历Map对象的4种方法

来源:互联网 发布:qq空间病毒式营销源码 编辑:程序博客网 时间:2024/06/02 07:11

首先 变量map

HashMap<String,String> map=new HashMap<String,String>();

1,利用Map的 Entry接口
for each 遍历,可以同时获得键和值

        for(Map.Entry<String,String> entry:map.entrySet()){            entry.getKey();            entry.getValue();        }   

2,利用 map对象的 keySet() values()
此时可以分别遍历键和值

        for(String key:map.keySet()){            System.out.println(key);        }        for(String value:map.values()){            System.out.println(value);        }

3,和1同理,但是需要借助 Iterator

        Iterator<Map.Entry<String,String>> iter=map.entrySet().iterator();        while(iter.hasNext()){            Map.Entry<String,String> entry=iter.next();            entry.getKey();            entry.getValue();        }

4,效率最低的一种,keySet中得到key值,再利用key,map.get(key) 得到value
(在同时使用键值时,最好用前两种)

        for(String key:map.keySet()){            String values=map.get(key);        }

另外,至于Map接口的内部接口Entry,在HashMap中实现如下(jdk1.8)

   static class Node<K,V> implements Map.Entry<K,V> {        final int hash;        final K key;        V value;        Node<K,V> next;        Node(int hash, K key, V value, Node<K,V> next) {            this.hash = hash;            this.key = key;            this.value = value;            this.next = next;        }        public final K getKey()        { return key; }        public final V getValue()      { return value; }        public final String toString() { return key + "=" + value; }        public final int hashCode() {            return Objects.hashCode(key) ^ Objects.hashCode(value);        }        public final V setValue(V newValue) {            V oldValue = value;            value = newValue;            return oldValue;        }        public final boolean equals(Object o) {            if (o == this)                return true;            if (o instanceof Map.Entry) {                Map.Entry<?,?> e = (Map.Entry<?,?>)o;                if (Objects.equals(key, e.getKey()) &&                    Objects.equals(value, e.getValue()))                    return true;            }            return false;        }    }