java集合框架之Map

Map:

一次添加一对元素(key->value)

双列集合,键值对

常用方法:

1、  添加

V put(K key , V value)会更新key对应的value,并返回被替换的value

2、  删除

clear():清空集合

V remove(K key) :根据指定的key删除这个键值对

3、  判断:

Boolean containsKey(key)

Boolean containsValue(value);

Boolean isEmpty();

4、  获取

Value get(key):通过键获取值,如果没有该键返回null。

Int size():获取键值对个数

Map常用子类:

Hashtable(1.0就有):内部结构是哈希表,是同步的,不允许null作为键或者是值

           Hashtable子类:Properties用于存储键值对型的配置信息,配合IO

HashMap:内部是哈希表,不同步,允许null作为键或者值

TreeMap:内部是二叉树,不同步,可以对集合中的键排序

demo:

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

public class App {

    public static void main(String[] args) {
        
        Map<Integer , String> map = new HashMap<Integer , String>();
        
        valuesTest(map);
        
    }
    /**
     * keySet方法返回map的键Set集合
     * @param map
     */
    public static void keySetTest(Map<Integer , String> map){
        
        map.put(1, "arg1");
        map.put(3, "arg3");
        map.put(2, "arg2");
        
        Set<Integer> keySet = map.keySet();
        
        Iterator<Integer> it = keySet.iterator();
        
        while(it.hasNext()){
            
            Integer key = it.next();
            System.out.println(map.get(key));
        }
    }
    /**
     * entrySet
     * 通过将map转给set实现
     * 该方法将key=>value映射关系作为对象存储到set集合中
     */
    public static void entrySetTest(Map<Integer , String> map){
        
        map.put(1, "arg1");
        map.put(3, "arg3");
        map.put(2, "arg2");
        /**
         * Map.Entry是个静态内部接口
         * 
         * interface Map{
         *     public static Entry{
         *     
         *     }
         * }
         */
        Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
        
        Iterator<Map.Entry<Integer, String>> it = entrySet.iterator();
        
        while(it.hasNext()){
            Map.Entry<Integer, String> temp = it.next();
            int key = temp.getKey();
            String value = temp.getValue();
            System.out.println(key + ":" + value);
        }
    }
    /**
     * values()返回map集合的值collection
     * @param map
     */
    public static void valuesTest(Map<Integer , String> map){
        
        map.put(1, "arg1");
        map.put(3, "arg3");
        map.put(2, "arg2");
        // 这里是Collection
        Collection<String> co = map.values();
        
        Iterator<String> it = co.iterator();
        
        while(it.hasNext()){
            
            System.out.println(it.next());
        }
    }
}
原文地址:https://www.cnblogs.com/orlion/p/4822483.html