zoukankan      html  css  js  c++  java
  • 33.Map

    1.概述

     

    2.Map的获取功能

     3.遍历

    方式1:

            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("001","张飞");
            hashMap.put("002","关于");
            hashMap.put("003","赵云");
            Set<String> stringSet = hashMap.keySet();
            for (String key:stringSet){
                System.out.println(key+":"+hashMap.get(key));
            }

    方式2:

          

            Set<Map.Entry<String, String>> entries = hashMap.entrySet();
            for (Map.Entry<String, String> m:entries){
                System.out.println(m.getKey()+":"+m.getValue());
            }

     方式3:

        只获取值

    26.  System.out.println("通过Map.values()遍历所有的value,但不能遍历key");  
    27.  for (String v : map.values()) {  
    28.   System.out.println("value= " + v);  
    29.  }  
    30. }  

     方式4:

    /**
     * default void forEach​(BiConsumer<? super K,​? super V> action)
     * 对此映射中的每个条目执行给定操作,直到处理完所有条目或操作引发异常。
     *      BiConsumer:
     *          这是一个功能接口,因此可以用作lambda表达式或方法引用的赋值目标。
     * --------------------------------------------------------------------------------
     *          @FunctionalInterface
     *          public interface BiConsumer<T,​U>
     *              其功能方法是accept(Object, Object) 。 
     */
    public class HashMapLearn {
        public static void main(String[] args) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("1", "1");
            hashMap.put("2", "2");
            hashMap.put("3", "3");
            hashMap.put("4", "4");
            hashMap.forEach((key, value) -> {
                System.out.println(key + ":" + value);
            });
        }

    补充:

    Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。

    HashMap的源码中发现了Entry的定义,原来他是HashMap的一个内部类,并且实现了Map.Entry接口:

    1.static class Entry<K,V> implements Map.Entry<K,V> {    
    2.    final K key;    
    3.    V value;    
    4.    Entry<K,V> next;    
    5.    final int hash;    
    6.    
    7.    /**  
    8.     * Creates new entry.  
    9.     */    
    10.    Entry(int h, K k, V v, Entry<K,V> n) {    
    11.        value = v;    
    12.        next = n;    
    13.        key = k;    
    14.        hash = h;    
    15.    }    
    16.    
    17.    public final K getKey() {    
    18.        return key;    
    19.    }    
    20.    
    21.    public final V getValue() {    
    22.        return value;    
    23.    }    
  • 相关阅读:
    【20210930】连岳摘抄
    【20211002】连岳摘抄
    网站首页head区代码规范(网页设计师必看)
    让你的VMware Workstation随主系统自动启动
    asp中使用图片验证码的方法
    文本筐怎样让它只能输入数字(以及怎么只能输入一个小数点和数字)
    asp通用分页函数
    系统安装秘技:精心打造WinXP万能GHOST(图)
    asp调用存储过程
    在 win2k3 下安装 webeasymail
  • 原文地址:https://www.cnblogs.com/luzhanshi/p/13166662.html
Copyright © 2011-2022 走看看