Java集合框架--Map接口

2022/9/7 1:23:05

本文主要是介绍Java集合框架--Map接口,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

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);});
    }
}

 

 

  

 

 

 

  



这篇关于Java集合框架--Map接口的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程