Map: Add one pair of elements at a time. Collection adds one element at a time.

A Map is also called a two-column Collection, and a Collection is called a single-column Collection. In fact, the map collection stores key-value pairs. Keys must be unique in the map collectionCopy the code

Common methods:

1. Add.

Value PUT (key,value): Returns the previous value associated with the key, or null if not.Copy the code

2, delete.

Void clear(): clears the map set. Value remove(key): Displays the key-value pair based on the specified key.Copy the code

3. Judge.

     boolean containsKey(key):

     boolean containsValue(value):

     boolean isEmpty();
Copy the code

4. Get.

Value get(key): Retrieves a value by key, or returns null if there is no key. Of course, you can return null to determine whether the specified key is included. Int size(): Gets the number of key-value pairs.Copy the code

Ex. :

     public static void main(String[] args) {
              Map<Integer,String> map = new HashMap<Integer,String>();
Copy the code

method(map);

method_2(map); } public static void method_2(Map<Integer,String> map){ map.put(8,"zhaoliu"); map.put(2,"zhaoliu"); map.put(7,"xiaoqiang"); map.put(6,"wangcai"); Collection<String> values = map.values(); Iterator<String> it2 = values.iterator(); while(it2.hasNext()){ System.out.println(it2.next()); } /* * The first way to iterate over a Map set is by converting a Map to a set. * Found another way. EntrySet. */ Set< map.entry <Integer, String>> entrySet = map.entryset (); */ Set< map.entry <Integer, String>> entrySet = map.entryset (); Iterator<Map.Entry<Integer, String>> it = entrySet.iterator(); while(it.hasNext()){ Map.Entry<Integer, String> me = it.next(); Integer key = me.getKey(); String value = me.getValue(); System.out.println(key+"::::"+value); } // The second way to iterate over the Map collection // fetch all the elements in the Map. // Get the value of each key through the map Set iterator. // Get the value of each key through the map Set. Set<Integer> keySet = map.keySet(); Iterator<Integer> it = keySet.iterator(); while(it.hasNext()){ Integer key = it.next(); String value = map.get(key); System.out.println(key+":"+value); }}Copy the code

Public static void method(Map<Integer,String> Map){// Student id and name

// Add elements. System.out.println(map.put(8, "wangcai")); //null System.out.println(map.put(8, "xiaoqiang")); // Wangcai stores the same key, the value will be overwritten. map.put(2,"zhangsan"); map.put(7,"zhaoliu"); / / delete. System.out.println("remove:"+map.remove(2)); / / judgment. System.out.println("containskey:"+map.containsKey(7)); / / access. System.out.println("get:"+map.get(6)); System.out.println(map); Outer.Inner.show(); }Copy the code

Common subclasses of Map:

| - Hashtable: internal structure is a hash table, are synchronous. Null is not allowed as a key, null as a value. | - Properties: used to store the key value of type configuration file information, can be combined and IO technology. | - HashMap: internal structure is a hash table, is not synchronized. Null is allowed as key and NULL as value. | - TreeMap: internal structure is a binary tree, is not synchronized. You can sort the keys in the Map collection.Copy the code

Example 1: Using HashMap

public class Person { public int hashCode() { final int prime = 31;

              int result = 1;

              result = prime * result + age;

              result = prime * result + ((name == null) ? 0 : name.hashCode());

              return result;

     }
Copy the code

Note: In this example, the hash value of the Person Object is the same as that of the equals(Object obj) method. In this example, the hash value of the Person Object is identical. If you implement these two methods, you can compare objects for equality and overwrite the value of the original object if they are equal. Implement the methods Source->Generate hashCode() and equals() and then select the properties to compare

public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() ! = obj.getClass()) return false; Person other = (Person) obj; if (age ! = other.age) return false; if (name == null) { if (other.name ! = null) return false; } else if (! name.equals(other.name)) return false; return true; } private String name; private int age; public Person() { super(); } public String getName() { return name; } public int getAge() { return age; } public Person(String name, int age) { super(); this.name = name; this.age = age; }Copy the code

}

import java.util.HashMap;

import java.util.Iterator;

public class ThreadDemo { public static void main(String[] args) { HashMap<Person, String> hMap = new HashMap<Person, String>();

Hmap. put(new Person("lisi", 23), "Beijing "); Hmap. put(new Person(" zhaolLiu ", 45), "Shanghai "); Hmap. put(new Person(" Xiaoqiang ", 56), "Beijing "); Hmap. put(new Person(" Wangcai ", 21), "dalian "); Hmap. put(new Person("lisi", 23), "Beijing "); Iterator<Person> it = hMap.keySet().iterator(); while (it.hasNext()) { Person key = it.next(); String value = hMap.get(key); System.out.println(key.getName() + ":" + key.getAge() + "---" + value); }}Copy the code

}

Example 2. Use of TreeMap.

package aaa;

public class Person {

     private String name;

     private int age;

     public Person() {

              super();

     }

     public  String  getName() {

              return name;

     }

     public int getAge() {

              return age;

     }

     public Person(String name, int age) {

              super();

              this.name = name;

              this.age = age;

     }
Copy the code

}

package aaa;

public class Student extends Person {

     public Student() {

              super();

     }

     public Student(String name, int age) {

              super(name, age);

     }
Copy the code

}

package aaa;

import java.util.TreeMap;

import java.util.Iterator;

public class ThreadDemo {

public static void main(String[] args) { TreeMap<Student, String> hMap = new TreeMap<Student, String>(new ComparetorByName()); Hmap. put(new Student("lisi", 23), "Beijing "); Hmap. put(new Student("zhaolliu", 45), "Shanghai "); Hmap. put(new Student("xiaoqiang", 56), "Beijing "); Hmap. put(new Student("wangcai", 21), "wangcai"); Hmap. put(new Student("lisi", 23), "Tokyo "); Iterator<Student> it = hMap.keySet().iterator(); while (it.hasNext()) { Person key = it.next(); String value = hMap.get(key); System.out.println(key.getName() + ":" + key.getAge() + "---" + value);Copy the code

Output result:

Lisi: 23 – Tokyo

Wangcai: 21 – dalian

Xiaoqiang: 56 – Beijing

Zhaolliu: 45 – Shanghai

}}Copy the code

}

Example 3. Example of using LinkedHashMap

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Set;

public class ThreadDemo {

     public static void main(String[] args) {

     LinkedHashMap<Integer, String> linkedHashMap=new LinkedHashMap<>();

     linkedHashMap.put(2, "sd");

     linkedHashMap.put(3, "qwdsa");

     linkedHashMap.put(1, "dfsd");

     linkedHashMap.put(9, "sewq");

     Iterator<Map.Entry<Integer, String>> iterator=linkedHashMap.entrySet().iterator();

     while (iterator.hasNext()) {

              Map.Entry<Integer, String> mEntry=iterator.next();

              Integer keyInteger=mEntry.getKey();

              String valueString=mEntry.getValue();

                               System.out.println(keyInteger+":"+valueString);
Copy the code

Output result:

2:sd

3:qwdsa

1:dfsd

9:sewq

The result is ordered

}}Copy the code

}

Exercise: “fdgavCBSACdfs” gets the number of occurrences of each letter in the string.

package aaa;

import java.util.Iterator;

import java.util.Map;

import java.util.TreeMap;

/ *

  • Practice:

  • “Fdgavcbsacdfs” gets the number of occurrences of each letter in the string.

  • The required print result is: A (2)b(1)… ;

  • Ideas:

  • Analysis of the results shows that there is a mapping relationship between letters and times. And there are many.

  • Many of them need to be stored. Containers that can store mappings are arrays and Map collections.

  • Is it a way of sequential numbering? No!

  • That’s using the Map collection. And found that the party that guarantees uniqueness has the order A, B, C…

  • So you can use the TreeMap collection.

  • This set should ultimately store correspondence between letters and degrees.

  • 1, since we operate on letters in a string, we first turn the string into an array of characters.

  • 2, iterate through the character array, using each letter as a key to look up the table in the Map collection.

  • If the letter key does not exist, the letter is stored in the Map collection as a value for key 1.

  • If the letter key exists, the value of the letter key is extracted and +1 is added, and the value after the letter and +1 is stored in the map set.

  • The same key value overrides. The number of times the letter is recorded.

  • 3. At the end of traversal, the map set records the occurrence times of all letters. oy.

* /

public class ThreadDemo {

/** * @param args */ public static void main(String[] args) { String str = "fdg+avAdc bs5dDa9c-dfs"; String s = getCharCount(str); System.out.println(s); } public static String getCharCount(String STR) {char[] CHS = str.tochararray (); // Define the map collection table. Map<Character,Integer> map = new TreeMap<Character,Integer>(); for (int i = 0; i < chs.length; i++) { if(! (chs[i]>='a' && chs[i]<='z' || chs[i]>='A' && chs[i]<='Z')) continue; // Query the map table with the letters in the array as keys. Integer value = map.get(chs[i]); map.put(chs[i], value==null? 1:value+1); } return mapToString(map); } private static String mapToString(Map<Character, Integer> map) { StringBuilder sb = new StringBuilder(); Iterator<Character> it = map.keySet().iterator(); while(it.hasNext()){ Character key = it.next(); Integer value = map.get(key); sb.append(key+"("+value+")"); } return sb.toString(); }Copy the code

}