Map接口与HashMap基本使用

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

/**
 * Map接口:
 * 1、键值对存储一组对象
 * 2、Key不能重复(唯一),Value可以重复
 * 3、具体的重点实现类:HashMap  TreeMap  Hashtable  LinkedHashMap
 */

public class MapDemo {
    public static void main(String[] args) {
        hashMap();
    }
    
    
    public static void hashMap() {
        Map<Integer,String> map = new HashMap<>();
        //Map的存储:先将(1,"Tom")new了一个Entry保存,然后将Entry再存入Map中,如此实现Map中键值的存储
        map.put(1, "Tom");  //存入Map
        map.put(2, "Jerry");
        map.put(3, "Lily");
        map.put(4, "Bob");
        
        //从Map中取值:通过key取value
        System.out.println(map.get(1));
        
        //Map的第一种遍历:这里的Entry<Integer,String> 就是存储在Map中的Entry对象
        //即遍历Map里面的entry生成一个Set集合
        //Set<Entry>,Set集合的泛型是Entry,而Entry的泛型又是Integer,String;所以写成:Set<Entry<Integer,String>>
        Set<Entry<Integer,String>> entry = map.entrySet();
        for(Entry e:entry) {   //
            System.out.println(e.getKey()+"->"+e.getKey());
        }
        
        //Map的第二种遍历:遍历key,然后通过key取值
        //遍历key生成一个Set集合,里面的泛型是Integer
        Set<Integer> keys = map.keySet();
        for(Integer k:keys) {
            System.out.println(map.get(k));
        }
        
        //Map的第三种遍历:直接遍历value
        //遍历Value生成一个Set集合,里面的泛型是String
        Collection<String> values = map.values();
        for(String v:values) {
            System.out.println(v);
        }
        
        //Map的第四种遍历:forEach(BiConsumer<? super K,? super V> action)
        //BiConsumer:是一个功能界面,因此可以用作lambda表达式或方法引用的赋值对象
        //这里参数(key,value)的类型省略了,可以带上也可以不带上(Integer key,String value)
        map.forEach((Key,value)->System.out.println(Key+"->"+value));
        
        //是否包含某key;返回boolean
        System.out.println(map.containsKey(5));
        
        
    }
    

}

猜你喜欢

转载自blog.csdn.net/weixin_33796205/article/details/87073906