Java's map

to sum up

Map has a mapping data used to save the relationship: with respect to the dictionary

  1. Therefore Map holds two sets of values ​​in the set, a set of values ​​stored in the Map Key, another group of the Map Value for storing
  2. Map of the key and value can be any type of reference data
  3. Map of Key must be unique, i.e., with any two Key Map object returns a false comparison method equals
  4. There is a one-way one to one relationship between Key and Value, that is, always find unique, Value determined by the specified Key.

HashMap method

public class Test02 {
    public static void main(String[] args) {
        //创建map集合
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("a",11);
        map.put("c",13);
        map.put("b", 9);
        System.out.println(map);//{a=11, b=9, c=13}
        
        //通过key获取value的值
        map.get("a");
        System.out.println(map.get("a"));//11
        
        //判断集合中是否包含指定key
        map.containsKey("b");
        System.out.println(map.containsKey("b"));
        
        //判断集合中是否包含指定value
        map.containsValue(11);
        System.out.println(map.containsValue(11));
        
        //集合长度
        map.size();
        System.out.println(map.size());
        
        Set<String> keys = map.keySet();//获取map中的key的集合
        map.values();//获取map中value的集合
        System.out.println(keys);
        System.out.println(map.values());
        
        //通过keySet遍历map集合
        for(String key: keys) {
            System.out.println("key="+key+",valus="+map.get(key));
        }
        //通过map.entrySet遍历map集合
        Set<Entry<String, Integer>> entry = map.entrySet();
        for(Entry<String, Integer> en : entry) {
            System.out.println("key="+en.getKey()+",valus="+en.getValue());
        }
        /**
         * TreeMap 存储 Key-Value 对时,需要根据 Key 对 key-value 对进行排序。TreeMap 可以保证所有的 Key-Value 对处于有序状态
         */
        
        //TreeMap自然排序是纯字典排序
        Map<String, Integer> map1 = new TreeMap<String, Integer>();
        map1.put("c",11);
        map1.put("a",12);
        map1.put("b",22);
        map1.put("ab",44);
        System.out.println(map1);//{a=12, ab=44, b=22, c=11}
                
    }
}

TreeMap methods

  1. When the Key-Value for storing TreeMap required Key key-value according to sort.
  2. TreeMap can guarantee that all of the Key-Value in an orderly state
  3. Natural ordering: All Key TreeMap must implement the Comparable interface, and all of Key should be the object of the same class, otherwise it will throw ClasssCastException
        //TreeMap自然排序是纯字典排序
        Map<String, Integer> map1 = new TreeMap<String, Integer>();
        map1.put("c",11);
        map1.put("a",12);
        map1.put("b",22);
        map1.put("ab",44);
        System.out.println(map1);//{a=12, ab=44, b=22, c=11}

Guess you like

Origin www.cnblogs.com/istart/p/12019936.html