Java集合框架--Map接口
2022-09-06 22:37:32

 

Map接口:

  1、采用键值对的形式存储对象

  2、Key不能重复,value可以重复

  3、主要实现类:HashMap   TreeMap    Hashtable

 

HashMap:

  public class HashMap<K,V> extends AbstractMap<K,V>

  implements Map<K,V> ,Cloneable,Serializable

  基于哈希表实现,允许key、value为 null,除了非同步和允许Null外其他的

  和Hashtable相似,此类不保证映射的顺序,也不保证顺序恒久不变。

代码示例

package com.collection.map;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MapDemo {
    public static void main(String[] args) {
        hashMap();
    }


    public static void hashMap(){
        Map<Integer,String> hm = new HashMap<>();
        hm.put(1,"AA");
        hm.put(2,"BB");
        hm.put(3,"CC");
        hm.put(4,"DD");

        //根据 Entry<K,V> 遍历
        Set<Map.Entry<Integer,String>> entry= hm.entrySet();
        for (Map.Entry en:entry){
            System.out.println(en.getKey()+":"+en.getValue());
        }

        System.out.println("*************************");
        //根据Keyset遍历
        Set<Integer> keyset=hm.keySet();
        for(Integer i:keyset){
            System.out.println(i+":"+hm.get(i));
        }

        //根据valueSet遍历
        System.out.println("*************************");
        Collection<String> co= hm.values();
        for(String s:co){
            System.out.println(s);
        }

        System.out.println("*************************");
        //JDK1.8新的foreach
        hm.forEach((k,v)->{System.out.println(k+":"+v);});
    }
}

 

 

  

 

 

 

  

本文摘自 :https://www.cnblogs.com/


更多科技新闻 ......