Java基础之集合函数-Map

(1)Map:元素是键值对 key:唯一,不可重复。****value:可重复遍历:先迭代遍历key的集合,再根据key得到value 。
(2)排序:SortedMap,元素自动对key排序

(3)HashMap:轻量级 线程不安全 允许key或者value是null
(4)Hashtable:重量级 线程安全 不允许key或者value是null
Properties:Hashtable的子类,key和value都是String
(5)TreeMap: 集合是指一个对象可以容纳了多个对象(不是引用),这个集合对象主要用来管理维护一系列相似的对象。

(6)遍历:foreach或者iterator,不能使用for

        HashMap map = new HashMap();
        map.put("one","zhangsan");
        map.put("two","lisi");
        map.put("three","wangwu");

/** *对于Map的三种方式遍历 1.keySet() 2.values() 3.entrySet() 三种方式得到Set之后, *都可以使用foreach或者iterator,不能使用for,因为数据结构决定的 */
    // 方式1: keySet()方法获取到Set(key)
    public static void printElements(HashMap map) {
        Set<Integer> set = map.keySet();
        for (Integer integer : set) {
            System.out.println(map.get(integer));
        }
    }

    // 方式2:values()方法获取到Collection(value)
    public void printElements(HashMap map) {
        Collection<String> collection = map.values();
        for (String string : collection) {
            System.out.println(string);
        }
    }

    // 方式3:entrySet()方法获取到Set<Entry<key,value>>
    public void printElements(HashMap map) {
        Set<Entry<Integer, String>> entries = map.entrySet();
        for (Entry<Integer, String> entry : entries) {
            System.out.println(entry.getValue());
        }
    }

    // 方式3:entrySet()方法获取到Set<Entry<key,value>>
    // for-each遍历
    public void printElements(HashMap map) {
        Set<Entry<Integer, String>> entries = map.entrySet();
        for (Entry<Integer, String> entry : entries) {
            System.out.println(entry.getValue());
        }
    }

    // 方式3:entrySet()方法获取到Set<Entry<key,value>>
    // iterator遍历
    public void printElements(HashMap map) {
        Set entries = map.entrySet();
        Iterator iter = entries.iterator();
        while(it.hasNext())
        {
            Map.Entry entry = (Map.Entry)iter.next();
         System.out.println(entry.getKey()+":"+entry.getValue());
        }
    }

(7)测试方法

public class MapTest {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String arg[]) {

        /** * Map * Map属于集合,但是不同于List、Set继承于Collection接口 * Map是key和value的映射集合,key就是一个集合 * Key必须惟一(重复只当作一个),value可以重复 */
        /* * HashMap : Map基于散列表的实现 */
        /* * TreeMap : 基于红黑树数据结构的实现 */
        HashMap map = new HashMap();
        map.put("s001", "aaa");
        map.put("s001", "bbb"); 
        map.put("s002", "ccc"); 
        System.out.println(map.size());
        System.out.println(map.get("s002"));
    }       
}

这里写图片描述

你可能感兴趣的:(java)