day21_Map collection and Collections tool classes

Keywords: Java

Overview of Map sets

In real life, we often see such a Collection: IP address and host name, ID number and personal, system user name and system user object, this one-to-one correspondence, is called mapping. Java provides a special Collection class to store the object of this object relationship, that is, the java.util.Map interface. By looking at the description of the map interface, we find that the Collection under the map interface is different from the Collection interface in the form of storing data. The main differences are as follows:

  • For the Collection in the Collection, the elements exist in isolation (understood as detail), and the elements stored in the Collection are stored in the form of elements one by one.
  • The collection elements in the Map exist in pairs (understood as husband and wife). Each element consists of a key and a value. You can find the corresponding value through the key.
  • Collections in the Collection are called single column collections, and collections in the Map are called double column collections.
  • The set in the Map cannot contain duplicate keys, and the values can be duplicate; Each key can only correspond to one value (this value can be a single value, or an array or collection value).

Basic functions of Map collection

Sample code

import java.util.HashMap;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
        //Create map object
        Map<String, String> map = new HashMap<>();
        //Add element map collection
        map.put("001", "Xiao Zhi");
        map.put("002", "Xiaomei");
        map.put("003", "Fat");
        map.put("004", "Xiao Hei");
        map.put("005", "master");
        System.out.println(map);//{001 = Xiao Zhi, 002 = Xiao Mei, 003 = Da Pang, 004 = Xiao Hei, 005 = Master}
        When using the put method, if the specified key does not exist in the set, there is no value corresponding to the key, null is returned, and the specified key value is added to the set;
        If the specified key exists in the set, the return value is the value corresponding to the key in the set (the value is the value before replacement), and the value corresponding to the specified key is replaced with the specified new value.
        String s = map.put("002", "Fat man");
        System.out.println(map);//{001 = Xiao Zhi, 002 = Da Pang, 003 = Da Pang, 004 = Xiao Hei, 005 = Master}

        // int size() the length of the set, that is, the number of key value pairs in the set
        int size = map.size();
        System.out.println(size);// 5

        // boolean isEmpty() determines whether the collection is empty
        boolean empty1 = map.isEmpty();

        // boolean containsKey(Object key) determines whether the collection contains the specified key
        boolean result1 = map.containsKey("001");
        boolean result2 = map.containsKey("006");

        // boolean containsValue(Object value) determines whether the collection contains the specified value
        boolean result3 = map.containsValue("aaa");
        boolean result4 = map.containsValue("Xiao Zhi");

        //  V remove(Object key) deletes the key value pair element according to the key
        String s1 = map.remove("001");
        String s2 = map.remove("007");
        System.out.println(s1);//Xiao Zhi
        System.out.println(map);//{002 = big fat, 003 = big fat, 004 = little black, 005 = Master}

        //  void clear() removes all key value pair elements

Get function of Map collection

Traversal of Map collection

Traversal of Collection: (1) foreach (2) traversal through Iterator object. The traversal of Map cannot support foreach because the Map interface does not inherit the Java. Lang. iteratable < T > interface and does not implement the Iterator iterator() method. You can only traverse in the following way:

(1) Separate traversal:

  • Traverse all key s individually
  • Traverse all value s individually

(2) Pairwise traversal:

  • Traverses objects of Map.Entry type, which is the internal interface of Map interface. Each Map has its own implementation class of Map.Entry. Storing data in Map actually stores the data of key - > value in the instance of Map.Entry interface, and then inserts the instantiated object of Map.Entry into the Map collection, as shown in the figure:

Method 1: separate traversal, the steps are as follows

  1. Get all the keys in the Map. Since the keys are unique, a Set collection is returned to store all the keys. Method tip: keyset()
  2. Traverse the Set set of keys to get each key.
  3. According to the key, get the value corresponding to the key. Method tip: get(K key)
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 * Map The first traversal method of
public class MyMap3 {
    public static void main(String[] args) {
        //Create a collection and add elements
        Map<String,String> map = new HashMap<>();
        map.put("1 Husband No","1 No. wife");
        map.put("2 Husband No","2 No. wife");
        map.put("3 Husband No","3 No. wife");
        map.put("4 Husband No","4 No. wife");
        map.put("5 Husband No","5 No. wife");

        //Get all keys
        Set<String> keys = map.keySet();
        //Traverse the Set to get each key
        for (String key : keys) {
            //Get the corresponding value through each key
            String value = map.get(key);
            System.out.println(key + "---" + value);

Entry key value pair object

We already know that there are two kinds of objects stored in the Map, one is called key and the other is called value. They are one-to-one correspondence in the Map. This pair of objects is also called an entry in the Map. Entry encapsulates the correspondence of key value pairs into objects. That is, the key value pair object, so that when we traverse the Map collection, we can obtain the corresponding key and corresponding value from each key value pair (entry) object. Since entry represents a pair of keys and values, it also provides methods to obtain corresponding keys and values:

  • public K getKey(): get the key in the Entry object.
  • public V getValue(): get the value in the Entry object.

Methods for obtaining all Entry objects are also provided in the Map collection:

  • Public Set < Map. Entry < K, V > > entryset(): get the Set of all key value pair objects in the Map Set (Set set).

Mode 2: traversal in pairs, the steps are as follows

  1. Get all key value pair (Entry) objects in the Map collection and return them in the form of Set collection. Method tip: entrySet().
  2. Traverse the Set set containing key value pair (Entry) objects to get each key value pair (Entry) object.
  3. Get the key and value in the Entry object through the key value pair (Entry) object. Method prompt: getkey() getValue()

Code example

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

public class MyMap3 {
    public static void main(String[] args) {
        //Create a collection and add elements
        Map<String, String> map = new HashMap<>();
        map.put("1 Husband No", "1 No. wife");
        map.put("2 Husband No", "2 No. wife");
        map.put("3 Husband No", "3 No. wife");
        map.put("4 Husband No", "4 No. wife");
        map.put("5 Husband No", "5 No. wife");

        // Get all entry objects
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        // Traverse to get each entry object
        for (Map.Entry<String, String> entry : entrySet) {
            //Resolve entry object
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + "My wife is:" + value);

Common implementation classes of Map interface: HashMap, TreeMap, LinkedHashMap and Properties. HashMap is the most frequently used implementation class of Map interface.

HashMap class


  • The bottom layer of HashMap is the hash table structure
  • Rely on hashCode method and equals method to ensure the uniqueness of keys
  • If the key is to store a custom object, you need to override the hashCode and equals methods

Case requirements

  • Create a HashMap collection. The key is student and the value is string. Store multiple elements and traverse.
  • It is required to ensure the uniqueness of the key: if the member variable values of the student object are the same, we think it is the same object

Student class

package Demo;

public class Student {
    private String name;
    private int age;

    public Student() {

    public Student(String name, int age) { = name;
        this.age = age;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals( : == null;

    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;

    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +

Define test class

package Demo;

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

public class HashMapDemo {
    public static void main(String[] args) {
        //Create a HashMap collection object
        HashMap<Student, String> hm = new HashMap<Student, String>();

        //Create student object
        Student s1 = new Student("Lin Qingxia", 30);
        Student s2 = new Student("Zhang Manyu", 35);
        Student s3 = new Student("Wang Zuxian", 33);
        Student s4 = new Student("Wang Zuxian", 33);

        //Add students to collection
        hm.put(s1, "Xi'an");
        hm.put(s2, "Wuhan");
        hm.put(s3, "Zhengzhou");
        hm.put(s4, "Beijing");

        //The first method: first get all the keys, and then find the corresponding value through each key
        Set<Student> keys = hm.keySet();
        for (Student key : keys) {
            String value = hm.get(key);
            System.out.println(key + "----" + value);


        //The second method: get all key value pair objects first. Then get each key and value inside
        Set<Map.Entry<Student, String>> entries = hm.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            Student key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + "----" + value);
                (Student key, String value) -> {
                    System.out.println(key + "----" + value);


TreeMap class

Implementation of NavigableMap based on red black tree. The map is sorted according to the natural order of its keys, or according to the Comparator provided when the map was created, depending on the construction method used. If the key stores custom objects, you need to implement the Comparable interface or give the Comparator sorting rules when creating TreeMap objects.

package com.itheima.maptest;

import java.util.Comparator;
import java.util.TreeMap;

 * Requirement: create a TreeMap set. The key is the student object and the value is the native place (String).
 *           Student attribute name and age, sorted by age and traversed.
public class Test1 {
    public static void main(String[] args) {
        TreeMap<Student,String> tm = new TreeMap<>(new Comparator<Student>() {
            public int compare(Student o1, Student o2) {
                int result = o1.getAge() - o2.getAge();
                result = result== 0 ? o1.getName().compareTo(o2.getName()) : result;
                return result;

        Student s1 = new Student("xiaohei",23);
        Student s2 = new Student("dapang",22);
        Student s3 = new Student("xiaomei",22);


                (Student key, String value)->{
                    System.out.println(key + "---" + value);

LinkedHashMap class

LinkedHashMap is a subclass of HashMap. This implementation differs from HashMap in that it maintains a double linked list that runs on all items. This linked list defines the iterative order, which is usually the order in which keys are inserted into the map (insertion order).

Properties class

The properties class is a subclass of Hashtable. Properties can be saved in or loaded from the stream. Each key and its corresponding value in the attribute list is a string. When accessing data, it is recommended to use setProperty(String key,String value) method and getProperty(String key) method.

Collections tool class

Collections is a tool class that operates on collections such as Set, List, and Map. Collections provides a series of static methods to sort, query and modify collection elements. It also provides methods to Set immutable collection objects and realize synchronous control over collection objects. Common methods are as follows:

  • public static <T> boolean addAll(Collection<? Super T > C, t... Elements) adds all specified elements to the specified collection.
  • public static <T> int binarySearch(List<? extends Comparable<? Super T > > list, T key) find the subscript of an element in the list set, but the element of the list must be t or a subclass object of T, and must be of comparable size, that is, it supports natural sorting. Moreover, the set must be ordered in advance, otherwise the result is uncertain.
  • public static <T> int binarySearch(List<? extends T> list,T key,Comparator<? Super T > c) find the subscript of an element in the list set, but the element of the list must be t or a subclass object of T, and the set must be sorted according to the rules of the c comparator in advance, otherwise the result is uncertain.
  • public static <T extends Object & Comparable<? super T>> T max(Collection<? Extensions T > Coll) find the largest element in the coll collection. The objects in the collection must be t or subclass objects of T, and support natural sorting
  • public static <T> T max(Collection<? extends T> coll,Comparator<? Super T > COMP) find the largest element in the coll set. The objects in the set must be t or subclass objects of T. find the largest element according to the comparator comp
  • public static void reverse(List<?> List) reverses the order of the elements in the specified list.
  • public static void shuffle(List<?> List) the elements of the list set are sorted randomly, similar to shuffling
  • public static <T extends Comparable<? Super T > > void sort (List < T > List) sorts the elements of the specified List set in ascending order according to the natural order of the elements
  • public static <T> void sort(List<T> list,Comparator<? Super T > C) sort the list set elements according to the order generated by the specified comparator
  • public static void swap(List<?> List, int i, int j) exchange the elements at I and j in the specified list set
  • public static int frequency(Collection<?> c. Object o) returns the number of occurrences of the specified element in the specified collection
  • public static <T> void copy(List<? super T> dest,List<? Extensions (T > src) copy the contents of src to dest
  • Public static < T > Boolean replaceall (List < T > List, T oldVal, T newVal): replaces all old values of the List object with new values
  • The Collections class provides multiple synchronizedXxx() methods, which can wrap the specified collection into a thread synchronized collection, so as to solve the thread safety problem when multiple threads access the collection concurrently
  • Multiple unmodifiableXxx() methods are provided in the Collections class, which return the unmodifiable view of the specified Xxx.

Create immutable collection

In the List, Set and Map interfaces, there are of methods that can create an immutable Set

  • This collection cannot be added, deleted or modified
  • However, it can be combined with the parameterized construction of the set to realize the batch addition of the set

In the Map interface, there is also an ofEntries method to improve the readability of the code

  • First, the key value pair will be encapsulated into an Entry object, and then the Entry object will be added to the collection


public class MyVariableParameter4 {
    public static void main(String[] args) {
        // Static < E > List < E > of (E... elements) creates a list collection object with the specified elements
        //Static < E > Set < E > of (E... elements) creates a Set set object with a specified element
        //Static < K, V > Map < K, V > of (E... elements) creates a Map collection object with a specified element



    private static void method4() {
        Map<String, String> map = Map.ofEntries(
                Map.entry("zhangsan", "Jiangsu"),
                Map.entry("lisi", "Beijing"));

    private static void method3() {
        Map<String, String> map = Map.of("zhangsan", "Jiangsu", "lisi", "Beijing", "wangwu", "Tianjin");

    private static void method2() {
        //There cannot be duplicate elements in the passed parameters.
        Set<String> set = Set.of("a", "b", "c", "d","a");

    private static void method1() {
        List<String> list = List.of("a", "b", "c", "d");

        //Batch addition of collections.
        //First, create an immutable collection by calling the List.of method. The formal parameter of the of method is a variable parameter.
        //Create an ArrayList set and add all the data in the immutable set to the ArrayList.
        ArrayList<String> list3 = new ArrayList<>(List.of("a", "b", "c", "d"));

Posted by Bizzle on Sun, 05 Sep 2021 16:17:22 -0700