Section 51: Collection Framework Map in Java

Keywords: Java REST

Title Map

Brief Book Author: Dashu Xiaosheng

Collection Framework Map in Java

01

Map provides three collection views:

  1. Key set
  2. Value set
  3. Key-Value Mapping Set
public String getWeek(int num){
 if(num<0 || num>7){
  throw new NoWeekException(num+"No corresponding week");
  String[] weeks = {"","Monday"...."Sunday"};
  return weeks[num];
 }
}

Sunday (Sunday), Monday (Monday), Tuesday (Tuesday), Wednesday (Wednesday), Thursday (Thursday), Friday (Friday), Saturday (Saturday)

java.util
 Interface Map<K,V>
Parameters:
K is the key for this mapping
 The value of V for this mapping

Knowing subinterfaces:

Bindings,ConcurrentMap<K,V>,ConcurrentNavigableMap<K,V>,LogicalMessageContext,MessageContext,NavigableMap<K,V>,SOAPMessageContext,SorteMap<K,V>

Knowing the implementation class:

AbstractMap,Attributes,AuthProvider,ConcurrentHashMap,ConcurrentSkipListMap,EnumMap,HashMap,Hashtable,IdentityHashMap,LinkedHashMap,PrinterStateReasons,Properties,Provider,RenderingHints,SimpleBindings,TabularDataSupport,TreeMap,UIDefaults,WeakHashMap

Implemented interfaces:

public interface Map<K,V>

There can be no duplicate keys in the mapping, and each key can only be mapped on one value.

Characteristics in Map Sets:

  1. Internal storage mode is in the form of key-value pairs
  2. Keys in Map s should be unique

Nested classes (internal):

Method Explain
Map.Entry<K,V> Static interface, static interface, mapping schema key-value pairs

Map method:

Method Explain
clear() The type is void, and all mapping relationships are removed from the mapping
containsKey(Object key) Returns the boolean type. If the mapping contains the specified key, it returns true and vice versa.
containsValue(Object value) Returns the boolean type, if one or more keys in the mapping are mapped to the specified value, returning true and vice versa
entrySet() The return type is Set < Map. Entry < K, V > Returns the mapping relationship contained in this mapping.
equals(Object o) The return type is boolean, comparing whether the specified object is equal to the mapping
get(Object key) Returns the value mapped by the specified key. If the mapping does not contain the mapping relationship of the key, it returns to null, which means no
hasCode() Returns an Int type, returning the hash code value of this mapping
isEmpty() The return type is boolean. If the mapping has no key-value mapping, it returns true and vice versa.
keySet() The return type is Set<E>, returning the Set view of all keys contained in this mapping
put(K key, V value) The method of establishing mapping relation and adding mapping relation to corresponding key and value
putAll(Map<? extends K, ? extends V> m) The return type is void, and all mapping relationships are copied from the specified mapping relationship to the mapping
remove(Object key) If there is a mapping relationship for this key, remove it
size() The return type is Int, returning the number of key-value mappings in this mapping relationship
values() The return type is Collection < V>, returning the Collection view of the values contained in this mapping

put

V put (E key, V value)

The corresponding key and value are mapped, and the method of adding the mapping relationship is established. If the mapping relationship existed before, the specified value will be replaced by the old value.

Parameters:

Key - The key for the specified Association
Value - The value of the specified Association

Errors that will be thrown:

Unsupported OperationException: put operation is not supported
 ClassCastException: Mapping relationships are not allowed
 NullPointerException: The specified key or value is null, and this mapping is not allowed to store
 Illegal ArgumentException: The specified key or value is not allowed to be stored in the map

General implementation classes:

HashMap

java.util
//Class HashMap < K, V >
java.lang.Object
 -> java.util.AbstractMap<K,V>
  -> java.util.HashMap<K,V>

Parameters:

K-is the corresponding key
 V-is the corresponding value

Implemented interfaces:

Serializable,Cloneable,Map<K,V>

Known subclasses:

LinkedHashMap,PrinterStateReasons

So:

public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

02

Map example:

import java.util.HashMap;
public class MapDemo {
 public static void main(String[] args){
  // Building map
  Map<String,String> map = new HashMap<String,String>();
 // Additive elements
  map.put("Monday", "Monday");
  mpa.put( ...// Add it on your own.
  map.put("Sunday", "Sunday");
  // When adding an element, if the key is the same, the value overrides
  map.put("Sunday", "SundayDemo");  // The value is covered.
 // Get value
 String value = map.get("Sunday"); // The key exists, the return value is null, and vice versa.
 // Delete elements
 String s = map.remove("Sunday"); // Delete the corresponding key-value pairs so that they are missing in the Map set
 }
}

How to get all the keys

Map<String,String> map = new HashMap<String,String>();
map.put("Monday", "Monday");
map.put("Sunday", "Sunday");

Using keySet

Set<String> keySet = map.keySet();
for(Iterator<String> it = keySet.iterator(); it.hasNext(); ){
 String key = it.next();
 String value = map.get(key);
 System.out.println(key + " : " + value);
}

You can use the foreach loop

for(String key : keySet){
 System.out.println(key + " = " + map.get(key));
}

entrySet

Set<Map.Entry<K,V>> entrySet()

To return the view of the mapping relation Set contained in this mapping, the mapping relation in the map set is stored in the set set.

Mapping relationship: the relationship between keys and values, the type of data type Map.Entry (internal) relationship

Set<Map.Entry<String,String>> entrySet = map.entrySet();
Iterator< Map.Entry<String,String> > it = entrySet.iterator();
while(it.hasNext(K,V)){
 Map.Entry<String,String> m = it.next();
 // Get key
 String key = m.getKey();
 // Get value
 String value = m.getValue();
 System.out.println(key + " : " + value);
}

Map.Entry<K,V>

java.util
//Interface Map.Entry<K,V>

Interface implementation class:

AbstractMap.SimpleEntry , AbstractMap.SimpleImmutableEntry

Interface:

public static interface Map.Entry<K,V>
// For mapping item-key-value pairs

Map.Entry<K,V>Method

Method:

Method Explain
equals(Object o) The return type is boolean, comparing the equality of the specified object with this item
getKey() Returns the key corresponding to this item
getValue() Returns the corresponding value for this item
hashCode() Return type int, return hash code value for this item
setValue(V value) Replace the corresponding value with the specified value
for(Map.Entry<String,String> m : map.entrySet()){
 String key = m.getKey();
 String value = m.getValue();
 System.out.println(key + " : " + value);
}
interface Map{
 public static interface Entry();
}

values()

The return type is Collection < V>, returning the Collection view of the values contained in this mapping

Collection<String> values = map.values();
for(String value : values){
 System.out.println("value:"+value);
}

Summary: Map - > entrySet () getKey () getValue () - > keySet () get (key) - > values ()

03

Collection Framework Map.png

Hashmap

public class HashMapDemo {
 public static void main(String[] args){
  Map<Student,String> map = new HashMap<Student,String>();
 // Additive elements
 map.put(new Student("da",12), "1");
 map.put(new Student("shu",13), "2");
 map.put(new Student("dashu",14), "3");
 // Remove data
 // Set<Student> keySet = map.keySet();
 // for(Student key : keySet){}
 for(Student key : map.keySet() ){
  String value = map.get(key);
  System.out.println(key.toString() + " : " + value);
 }
 }
}
public class Student implements Comparable<Student>{
 private String name;
 private int age;
 public Student(){
  super();
 }
 public Student(String name, int age){
  super();
  this.name = name;
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name; 
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age){
  this.age = age;
 }
 @Override 
 public String toString() {
  return "Student [name = " + name +",age = " + age + "]";
 }
 @Override
 public int hasCode() {
  final int prime = 31;
  int result = 1;
  result = prime + result + age;
  result = prime + result + ((name == null) ? 0 : name.hashCode());
  return result;
 }
 @Override
 public boolean equals(Object obj){
  if(this == obj)
   return true;
  if(obj == null)
   return false;
  if(getClass() != obj.getClass() )
   return false;
  Student other = (Student) 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;
 }
 @Override
 public int  compareTo(Student o){
  int temp = this.age - o.age;
  
  return temp == 0? this.name.compareTo(o.name) : temp;
 }
}

TreeMap

public class TreeMapDemo{
 public static void main(String[] args){
   Map<Student, String> map = new TreeMap<Student, String>(new ComparatorByName());
 // Additive elements
 map.put(new Student("da",12), "1");
 map.put(new Student("shu",13), "2");
 map.put(new Student("dashu",14), "3");
 // Remove data
 for(Map.Entry<String,String> m : map.entrySet()){
  Student key = m.getKey();
  String value = m.getValue();
  System.out.println(key + " : " + value);
 }
 }
}
public class ComparatorByName implements Comparator<Student>{
 @Override
 public int compare(Student o1, Student o2){
  int temp = o1.getName().compareTo(o2.getName());
  return temp == 0 ? o1.getAge() - o2.getAge() : temp;
 }
}

04

Example:

public class CollectionsDemo {
   public static void main(String[] args) {
      Map m = new HashMap(); 
      m.put("da", "8");
      m.put("shu", "9");
      m.put("dashu", "10");
      m.put("dashucoding", "12");
      System.out.println(m);
   }
}

Java Map Collection Class

The most commonly used collection classes are List and Map. The implementation classes of List include ArrayList and Vector. List can be changed in size, suitable for building, storing, and manipulating lists of any type of object elements.

Map is more general. Map collection classes are used to store element pairs. They are key-value pairs. Each key maps to a value. Understandably, List can be regarded as Map of numeric keys, but they have nothing to do with each other.

All key-value pairs - entrySet()
All keys - keySet()
Value - values()

Iterator keyValues = map.entrySet().iterator();
Iterator keys = map.keySet().iterator();
Iterator values = map.values().iterator();

entrySet(): Returns the Set view of the mapping contained in the Map.
keySet(): Returns the Set view of the key contained in the Map.
values(): Returns the Collection view of the values contained in the Map.

For the rest of my life, you are the only one.
Brief Book Author: Dashu Xiaosheng
Post90s handsome young man, good development habits; ability to think independently; initiative and good communication
Brief Book Blog: https://www.jianshu.com/u/c785ece603d1

epilogue

  • Next, I will continue to explain other knowledge in depth. I am interested in continuing to pay attention to it.
  • A little gift or a little compliment

Posted by Charles Wong on Thu, 16 May 2019 03:13:06 -0700