【最全】Java中Map集合遍历的方式

Map集合的遍历方式

  先看下Map集合的部分源码:

package java.util;

import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.io.Serializable;


public interface Map<K,V> {
   

    /**
     * Returns the number of key-value mappings in this map. 
     * @return the number of key-value mappings in this map
     */


    //返回的是集合的大小
    int size();

    /**
     * Returns <tt>true</tt> if this map contains no key-value mappings.
     */

    // 判断集合中是否包含键值对 的元素
    boolean isEmpty();

    /**
     * Returns <tt>true</tt> if this map contains a mapping for the specified
     * key. 
     */

    // 是否包含这个键
    boolean containsKey(Object key);

    /**
     * Returns <tt>true</tt> if this map maps one or more keys to the
     * specified value.  
     */

    // 是否包含这个值
    boolean containsValue(Object value);

    /**
     * Returns the value to which the specified key is mapped,
     * 
     */

    // 返回的是包含这个键的值
    V get(Object key);

    // Modification Operations

    /**
     * Associates the specified value with the specified key in this map
     * (optional operation).  
     */

    // 将键值对添加到Map集合中
    V put(K key, V value);

    /**
     * Removes the mapping for a key from this map if it is present
     * (optional operation). 
     */

    // 删除集合中键对应的值
    V remove(Object key);


    // Bulk Operations

    /**
     * Copies all of the mappings from the specified map to this map
     * (optional operation).  The effect of this call is equivalent to that
     * of calling {@link #put(Object,Object) put(k, v)} on this map once
     * for each mapping from key <tt>k</tt> to value <tt>v</tt> in the
     * specified map.  The behavior of this operation is undefined if the
     * specified map is modified while the operation is in progress.
     *
     * @param m mappings to be stored in this map
     * @throws UnsupportedOperationException if the <tt>putAll</tt> operation
     *         is not supported by this map
     * @throws ClassCastException if the class of a key or value in the
     *         specified map prevents it from being stored in this map
     * @throws NullPointerException if the specified map is null, or if
     *         this map does not permit null keys or values, and the
     *         specified map contains null keys or values
     * @throws IllegalArgumentException if some property of a key or value in
     *         the specified map prevents it from being stored in this map
     */
    void putAll(Map<? extends K, ? extends V> m);

    /**
     * Removes all of the mappings from this map (optional operation).
     * The map will be empty after this call returns.
     *
     * @throws UnsupportedOperationException if the <tt>clear</tt> operation
     *         is not supported by this map
     */
    void clear();


    // Views

    /**
     * @return a set view of the keys contained in this map
     */

    // 返回的是
    Set<K> keySet();

    /**
     * Returns a {@link Collection} view of the values contained in this map.
    
     * @return a collection view of the values contained in this map
     */
    
    // 返回的是Map集合中的值

    Collection<V> values();

    /**
     *
     *
     * @return a set view of the mappings contained in this map
     */

    // 返回的是map集合中的键值对的映射,也就是键值对
    Set<Map.Entry<K, V>> entrySet();

    /**
     * A map entry (key-value pair).  
     */

    // 获取的是键值对
    interface Entry<K,V> {
        /**
         * Returns the key corresponding to this entry.
         *
         * @return the key corresponding to this entry
         * @throws IllegalStateException implementations may, but are not
         *         required to, throw this exception if the entry has been
         *         removed from the backing map.
         */
        K getKey();

        /**
         * Returns the value corresponding to this entry.  If the mapping
         * has been removed from the backing map (by the iterator's
         * <tt>remove</tt> operation), the results of this call are undefined.
         *
         * @return the value corresponding to this entry
         * @throws IllegalStateException implementations may, but are not
         *         required to, throw this exception if the entry has been
         *         removed from the backing map.
         */
        V getValue();

        /**
         * Replaces the value corresponding to this entry with the specified
         * value (optional operation).  (Writes through to the map.)  The
         * behavior of this call is undefined if the mapping has already been
         * removed from the map (by the iterator's <tt>remove</tt> operation).
         *
         * @
         */
        V setValue(V value);

        /**
         * Compares the specified object with this entry for equality.
      
         */
        boolean equals(Object o);

        /**
         * Returns the hash code value for this map entry.  
         */
        int hashCode();

        /**
         * Returns a comparator that compares {@link Map.Entry} in natural order on key.
         *
         * <p>The returned comparator is serializable and throws {@link
         * NullPointerException} when comparing an entry with a null key.
         *
         * @param  <K> the {@link Comparable} type of then map keys
         * @param  <V> the type of the map values
         * @return a comparator that compares {@link Map.Entry} in natural order on key.
         * @see Comparable
         * @since 1.8
         */
        public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getKey().compareTo(c2.getKey());
        }

        /**
         * Returns a comparator that compares {@link Map.Entry} in natural order on value.
         *
         * <p>The returned comparator is serializable and throws {@link
         * NullPointerException} when comparing an entry with null values.
         *
         * @param <K> the type of the map keys
         * @param <V> the {@link Comparable} type of the map values
         * @return a comparator that compares {@link Map.Entry} in natural order on value.
         * @see Comparable
         * @since 1.8
         */
        public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getValue().compareTo(c2.getValue());
        }

       
  Map<Integer,String> map = new HashMap<>();
        map.put(1, "shitian");
        map.put(2, "wangca");
        map.put(3, "sss");

 ① 遍历方式一:通过Map的key的值获取value值,使用的是   V get(Object key),获取键的值

        // 集合的键是一个Set集合,通过map.get(key)获取集合的值
        Set<Integer> keys = map.keySet();

        for (Integer key : keys) {
            System.out.println("键是 :" + key + "值是:" + map.get(key));
        }

 ② 遍历方式二:通过调用Map集合的values()获取所有键的值

    Collection<String> values = map.values();
        for (String s : values) {
            System.out.println("值:" + s);
        }

③ 通过迭代器遍历整个键值对的集合

        // map.entrySet()获取键值对的集合,然后通过迭代器进行遍历
        // 键值对的集合是通过Map.Entry<Integer,String>来接收的
        // Map中的内部类Entry,内部类里面有getKey()和getValue()的方法
        
        Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer,String> maps = iterator.next();
            int key = maps.getKey();
            String value = maps.getValue();
            System.out.println(key + "----" + value);

      Map.Entry是Map的一个内部接口。对于Map中提供的一些常用方法,如map.keySet()、map.entrySet()、map.values()等方法大多数人都不是很熟悉。map.keySet()方法返回值是Map中key值的集合;map.entrySet()的返回值是一个Set集合,Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示的是Map中的一个实体(key-value)。接口中有我们常用的getKey(),getValue方法。

④ 通过返回键值对的映射,Set进行接收,增强for循环进行遍历

        Set<Map.Entry<Integer, String>> set = map.entrySet();
        for (Map.Entry<Integer, String> entry : set) {
            System.out.println(entry.getKey() + "--" + entry.getValue());

 

猜你喜欢

转载自blog.csdn.net/Sunshineoe/article/details/115362216