📜  Java Map接口

📅  最后修改于: 2020-10-12 10:01:41             🧑  作者: Mango

Java Map接口

映射包含基于键的值,即键和值对。每个键和值对称为一个条目。映射包含唯一键。

如果必须基于键来搜索,更新或删除元素,则“地图”很有用。

Java Map层次结构

有两个用于在Java中实现Map的接口:Map和SortedMap,以及三个类:HashMap,LinkedHashMap和TreeMap。 Java Map的层次结构如下:

映射不允许重复的键,但是您可以有重复的值。 HashMap和LinkedHashMap允许空键和值,但是TreeMap不允许任何空键或值。

不能遍历Map,因此您需要使用keySet()或entrySet()方法将其转换为Set。

Class Description
HashMap HashMap is the implementation of Map, but it doesn’t maintain any order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It maintains ascending order.

Map界面的有用方法

Method Description
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) It is used to delete an entry for the specified key.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
Set> entrySet() It returns the Set view containing all the keys and values.
void clear() It is used to reset the map.
V compute(K key, BiFunction remappingFunction) It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function mappingFunction) It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer action) It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
boolean isEmpty() This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction remappingFunction) If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction function) It replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection view of the values contained in the map.
int size() This method returns the number of entries in the map.

Map.Entry接口

Entry是Map的子接口。因此,将通过Map.Entry名称对其进行访问。它返回地图的集合视图,其元素属于此类。它提供了获取关键和价值的方法。

Map.Entry接口的方法

Method Description
K getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
V setValue(V value) It is used to replace the value corresponding to this entry with the specified value.
boolean equals(Object o) It is used to compare the specified object with the other existing objects.
static ,V>
Comparator> comparingByKey()
It returns a comparator that compare the objects in natural order on key.
static Comparator> comparingByKey(Comparator cmp) It returns a comparator that compare the objects by key using the given Comparator.
static >
Comparator> comparingByValue()
It returns a comparator that compare the objects in natural order on value.
static Comparator> comparingByValue(Comparator cmp) It returns a comparator that compare the objects by value using the given Comparator.

Java Map示例:非泛型(旧样式)

//Non-generic
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}

输出:

1 Amit
2 Jai
5 Rahul
6 Amit

Java Map示例:通用(新样式)

import java.util.*;
class MapExample2{
 public static void main(String args[]){
  Map map=new HashMap();
  map.put(100,"Amit");
  map.put(101,"Vijay");
  map.put(102,"Rahul");
  //Elements can traverse in any order
  for(Map.Entry m:map.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

输出:

102 Rahul
100 Amit
101 Vijay

Java Map示例:compareByKey()

import java.util.*;
class MapExample3{
 public static void main(String args[]){
Map map=new HashMap();    
  map.put(100,"Amit");  
  map.put(101,"Vijay");  
  map.put(102,"Rahul"); 
      //Returns a Set view of the mappings contained in this map    
      map.entrySet()
  //Returns a sequential Stream with this collection as its source
  .stream()
  //Sorted according to the provided Comparator
  .sorted(Map.Entry.comparingByKey())
  //Performs an action for each element of this stream
  .forEach(System.out::println);
 }
}

输出:

100=Amit
101=Vijay
102=Rahul

Java Map示例:降序比对

import java.util.*;
class MapExample4{
 public static void main(String args[]){
Map map=new HashMap();    
  map.put(100,"Amit");  
  map.put(101,"Vijay");  
  map.put(102,"Rahul");  
      //Returns a Set view of the mappings contained in this map  
  map.entrySet()
  //Returns a sequential Stream with this collection as its source
  .stream()
  //Sorted according to the provided Comparator
  .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
  //Performs an action for each element of this stream
  .forEach(System.out::println);
 }
}

输出:

102=Rahul
101=Vijay
100=Amit

Java地图示例:compareByValue()

import java.util.*;
class MapExample5{
 public static void main(String args[]){
Map map=new HashMap();    
  map.put(100,"Amit");  
  map.put(101,"Vijay");  
  map.put(102,"Rahul");  
      //Returns a Set view of the mappings contained in this map  
  map.entrySet()
  //Returns a sequential Stream with this collection as its source
  .stream()
  //Sorted according to the provided Comparator
  .sorted(Map.Entry.comparingByValue())
  //Performs an action for each element of this stream
  .forEach(System.out::println);
 }
}

输出:

100=Amit
102=Rahul
101=Vijay

Java Map示例:降序比较

import java.util.*;
class MapExample6{
 public static void main(String args[]){
Map map=new HashMap();    
  map.put(100,"Amit");  
  map.put(101,"Vijay");  
  map.put(102,"Rahul");  
     //Returns a Set view of the mappings contained in this map  
 map.entrySet()
 //Returns a sequential Stream with this collection as its source
 .stream()
 //Sorted according to the provided Comparator
 .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
 //Performs an action for each element of this stream
 .forEach(System.out::println);
 }
}

输出:

101=Vijay
102=Rahul
100=Amit