Java Collections Framework interfaces --Map

The third stage of learning JAVA common objects

Collections Framework --Map collection

In actual demand, we often encounter such a problem, many of the data, to find some of the information by its number, and thus to view or modify, such as student information inquiry by student number. Today we are introducing a collection Map can be very good to help us achieve this demand

(A) Overview and features

(1 Overview

Map is set on the storing element (element pairs are referred to, also known as keys and key-value pairs) it is mapped to the key value of the object. A map can not contain duplicate keys, and each key can be mapped to at most one value.

How to understand it?

Key (key): value is the number you stored value (value): what you want to store data

You can be approximately understood to be the key index, stored value based on the key, each key has its corresponding value. Both of which it is the corresponding 1,1

However, before the subscript is an integer, but the keys can Map any type of object.

Map Collection difference between the set and the set?

  • Map storage element is set in pairs, Map key set is unique, reproducible value
  • Collection set of storage elements is occurring alone, Collection subclass Set is unique, List is repeatable.
  • Map data structure value for a set of valid keys, nothing to do with values, data structures Collection is a set of elements for effective

(2) Function

A: Adding functionality

//添加元素
V put(K key,V value)   
    
//如果键是第一次存储,就直接存储元素,返回null
//如果键不是第一次存在,就用值把以前的值替换掉,返回以前的值 

B: Delete function

//移除所有的键值对元素
void clear()

//根据键删除键值对元素,并把值返回
V remove(Object key)

C: judgment function

//判断集合是否包含指定的键
boolean containsKey(Object key)

//判断集合是否包含指定的值
boolean containsValue(Object value)

//判断集合是否为空
boolean isEmpty()

D: acquisition function

//将map集合中的键和值映射关系打包为一个对象
Set<Map.Entry<K,V>> entrySet()

//根据键获取值
V get(Object key)

//获取集合中所有键的集合
Set<K> keySet()

//获取集合中所有值的集合
Collection<V> values()

E: length feature

//返回集合中的键值对的对数
int size()

Traversal (B) Map collection

package cn.bwh_01_iterator;

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

public class MapDemo {
    public static void main(String[] args) {
        Map<String, String> hm = new HashMap<String, String>();
        hm.put("bwh002", "i");
        hm.put("bwh001", "love");
        hm.put("bwh003", "you");

        //方式一 键找值
        Set<String> set = hm.keySet();

        //迭代器遍历
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String value = hm.get(key);
            System.out.println(key + "---" + value);
        }

        //增强for遍历
        for (String key : set) {
            String value = hm.get(key);
            System.out.println(key + "---" + value);
        }

        //方式二 键值对对象找键和值(推荐)
        Set<Map.Entry<String, String>> set2 = hm.entrySet();

        //迭代器遍历
        Iterator<Map.Entry<String, String>> it2 = set2.iterator();
        while (it2.hasNext()) {
            //返回的是封装了key和value对象的Map.Entry对象
            Map.Entry<String, String> entry = it2.next();
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + "---" + value);

        }

        //增强for遍历
        for (Map.Entry<String, String> me : set2) {
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key + "---" + value);
        }
    }
}

(C) Map and subclasses summary

Map (double set of columns)

  • Map data structure of the key valid only for the set, irrespective of the value.

  • Key is stored in the form of an element, unique keys, values ​​can be repeated

HashMap

  • The underlying data structure is a hash table, thread-safe, high efficiency

  • Hash table depends on two methods: hashCod () and equals ()

  • The order of execution:

    • First determines hashCode () values ​​are identical
      • Is: Continue equals (), look at the return value
        • It is true: Description elements repeat, do not add
        • It is false: it is added directly to the collection
      • No: directly added to the collection
  • finally:

  • Automatically generated hashCode () and equals () to

LinkeHashMap

  • Underlying data structure is a linked list and hash tables

  • A list of elements to ensure the orderly

  • By a hash table to ensure that the only element

Hashtable

  • The underlying data structure is a hash table
  • ...... two hash table depends automatically generated hashCode () and equals () to

TreeMap

  • The underlying data structure is a red-black tree (balanced binary tree is a self)

How to ensure the uniqueness of elements?

  • According to the comparison of the return value is 0 to decide

How to ensure ordering two elements of it?

  • Natural ordering (comparative element includes a)
    • Let earth element belongs achieve comparable Interface
  • Sorting comparator (set includes comparative)
    • Let set receiving a comparator to achieve the object of class

Can be nested

Set of nested HashMap HashMap

HashMap set of nested ArrayList

ArrayList set of nested HashMap

HashMap<String, ArrayList > hm = new HashMap<String, ArrayList >

1: Hashtable and HashMap difference?

**Hashtable**:线程安全,效率低。不允许null键和null值

**HashMap**:线程不安全,效率高。允许null键和null值

(In fact, that is used to replace HashMap Hashtable, like ArrayList as an alternative vector)

2: List, Set, Map interfaces such as whether the child inherited Map interface?

List, Set is not inherited from the Map interface, they are inherited from the Collection interface

Map interface itself is a top level interface

Needs sorting: TreeMap

It requires no sorting: HashMap

I do not know the specific needs: HashMap

(Iv) Classic Case

Number (1) Statistics string of characters appearing

import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

/*
 * 案例(统计字符串中字符出现的次数)
 * 需求:
 *      获取一个字符串出现的次数
 * 分析:
 *      A:定义一个字符串(或者键盘录入)
 *      B: 定义一个TreeMap集合
 *              键:Character
 *              值:Integer
 *      C:把字符串转换为字符数组
 *      D: 遍历字符数组,得到每一个字符
 *      E: 拿刚才得到的字符作为键去集合中找,看返回值
 *              是 null:说明该键不存在,就把该字符串作为键,1作为值去存储
 *              不是 null:说明该键存在,就把值加 1 然后重写存储该键和值
 *      F: 定义字符串缓冲区变量
 *      G:遍历集合,得到该建和值,按照要求拼接
 *      H:最后把字符串缓冲区转换为字符串输出
 */
 
public class CountDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入需要统计的数据");
        String line = sc.nextLine();

        Map<Character, Integer> tm = new TreeMap<Character, Integer>();
        char[] chs = line.toCharArray();
        for (char ch : chs) {
            Integer i = tm.get(ch);
            if (i == null) {
                tm.put(ch, 1);
            } else {
                i++;
                tm.put(ch, i);
            }
        }

        StringBuilder s = new StringBuilder();
        Set<Character> set = tm.keySet();
        for (Character key : set) {
            Integer value = tm.get(key);
            s.append(key).append("(").append(value).append(")" + " ");
        }
        String result = s.toString();
        System.out.println("result: " + result);
    }
}

//运行结果
请输入需要统计的数据
HelloWorld
result: H(1) W(1) d(1) e(1) l(3) o(2) r(1) 

(2) Analog Landlords Case

Before explaining this case, we start to understand a case we need to know the following knowledge points

Collections Tools

Collections: it is for a set of tools to manipulate classes are static methods.

Interview questions:

Collection and Collections of the difference?

Collection : the interface is the top single collection, there are sub-interfaces List and Set. (Map is a two-column)

The Collections : is a collection of tools for the operation, there is the collection and sorting of binary method to find

Static methods of Collections

//排序 默认情况下是自然顺序。
public static <T> void sort(List<T> list)

//二分查找
public static <T> int binarySearch(List<?> list,T key)

//最大值
public static <T> T max(Collection<?> coll)

//反转(逆序排序)
public static void reverse(List<?> list)

//随机置换(犹如洗牌,每次运行结果不一样)
public static void shuffle(List<?> list)

如果同时有自然排序和比较器排序,以比较器排序为主(也就是说,当同时实现了Student类的自然排序(implements Comparable<Student>)以及比较器排序的话(new Comparator<Student>()),比较器排序会覆盖自然排序)
//斗地主案例代码
package cn.bwh_03_PokerGame;

import java.util.*;

public class PokerGame {
    public static void main(String[] args) {
        HashMap<Integer, String> hm = new HashMap<Integer, String>();
        ArrayList<Integer> array = new ArrayList<Integer>();

        String[] colors = {"♥", "♠", "♣", "♦"};
        String[] numbers = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};

        int index = 0;
        for (String number : numbers) {
            for (String color : colors) {
                String poker = color.concat(number);
                hm.put(index, poker);
                array.add(index);
                index++;
            }
        }

        hm.put(index, "小王");
        array.add(index);
        index++;
        hm.put(index, "大王");
        array.add(index);
        index++;

        //洗牌
        Collections.shuffle(array);

        //发牌(发的是编号,为了保证编号是排序的,使用TreeSet接收)
        TreeSet<Integer> player1 = new TreeSet<Integer>();
        TreeSet<Integer> player2 = new TreeSet<Integer>();
        TreeSet<Integer> player3 = new TreeSet<Integer>();
        TreeSet<Integer> handcards = new TreeSet<Integer>();

        for (int x = 0; x < array.size(); x++) {
            if (x >= array.size() - 3) {
                handcards.add(array.get(x));
            } else if (x % 3 == 0) {
                player1.add(array.get(x));
            } else if (x % 3 == 1) {
                player2.add(array.get(x));
            } else if (x % 3 == 2) {
                player3.add(array.get(x));
            }
        }

        System.out.println("---------------------欢乐斗地主----------------------");
        //看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)
        lookpocker("player1", player1, hm);
        lookpocker("player2", player2, hm);
        lookpocker("player3", player3, hm);
        lookpocker("预留", handcards, hm);
    }

    //看牌功能实现
    public static void lookpocker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) {
        System.out.println(name + "的牌是:");
        for (Integer key : ts) {
            String value = hm.get(key);
            System.out.print(value + " ");
        }
        System.out.println();
    }
}

end:

If there are any deficiencies, or content in the wrong place, welcome to give me a shout advice, crab everyone! ^ _ ^

If you can help, then it is to pay attention to me! (Updated series of articles will be the first time the public number)

Here we are strangers, all in the dream and work for their own ❤

Push a stick original Java technology public numbers: more than ten days over two

Guess you like

Origin www.cnblogs.com/ideal-20/p/11161598.html