Map interface in java

Map interface:

A map represents an object with key-value pair.  A map cannot contain duplicate keys and one key can map to at most one value.

Commonly used methods of Map interface:

1. clear(): Removes all key-value pairs from this map.

Syntax:

public void clear()

2. containsKey(Object k): Returns true if this map contains specified key otherwise returns false.

Syntax:

public boolean containsKey(Object k)

3. (Object v): Returns true if this map contains specified value otherwise returns false.

Syntax:

public boolean containsValue(Object v)

4. entrySet(): Returns a Set that contains the entries of this map. The set contains objects of type Map.Entry. It provides a set-view of this map.

Syntax:

public Set entrySet().

5. equals(Object obj): Returns true if specified object equals to this map otherwise returns false.

Syntax:

public boolean equals(Object obj)

6. get(Object k): Returns the value associated with the specified key.

Syntax:

public Object get(Object k)

7. hashCode(): Returns the hash code for this map.

Syntax:

public int hashCode()

8. isEmpty(): Returns true if this map is empty otherwise returns false.

Syntax:

public boolean isEmpty()

9. keySet(): Returns a Set that contains the keys in this map. This method provides a set-view of the keys in this map.

Syntax:

public Set keySet()

10. put(Object k, Object v): Puts an entry in this map, overwriting any previous value associated with the specified key. Returns previous value linked to the key. Return null if the key does not already exist.

Syntax:

public Object put(Object k, Object v)

11. putAll(Map m): Puts all the entries from m into this map.

Syntax:

public void putAll(Map m)

12. remove(Object k): Removes the entry whose key equals to specified key from this map. Returns the value to which this map previously associated with a specified key, or null if the map contained no mapping for the key.

Syntax:

public Object remove(Object k)

13. size(): Returns the number of entries in this map.

Syntax:

public int size()

14. values(): Returns a collection containing the values in this map. This method provides a collection-view of the values in this map.

Syntax:

public Collection values()

 A simple example of HashMap class to explain few methods of Map interface.

 HashMapTest.java

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
 
/**
 * This class is used to show the HashMap functionality.
 * @author w3spoint
 */
public class HashMapTest {
	public static void main(String args[]){
		//Create HashMap object.
		Map hashMap = new HashMap();
 
		//Add objects to the HashSet.
		hashMap.put(4, "Roxy");
		hashMap.put(2, "Sunil");
		hashMap.put(5, "Sandy");
		hashMap.put(1, "Munish");
		hashMap.put(3, "Pardeep");
 
		//Print the HashMap object.
		System.out.println("HashMap elements:");
		System.out.println(hashMap);
 
		//Get an iterator
		Set set=hashMap.entrySet();  
		Iterator iterator=set.iterator();  
 
		//Print the HashMap elements using iterator.
		System.out.println("HashMap elements using iterator:");
		while(iterator.hasNext()){
		   Map.Entry mapEntry=(Map.Entry)iterator.next();  
		   System.out.println("Key: " + mapEntry.getKey() + ", " +
		   		"Value: " + mapEntry.getValue());  
		}  
	}
}

Output:

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
HashMap elements using iterator:
Key: 1, Value: Munish
Key: 2, Value: Sunil
Key: 3, Value: Pardeep
Key: 4, Value: Roxy
Key: 5, Value: Sandy

Map.Entry Interface:

Being the subinterface of Map, an entry can be accessed by Map.Entry name. A collection-view of the map (whose elements are of this class) is returned by the entry. To get key and value, it facilitates methods.

Map.Entry interface Methods:

Method Description
K getKey() It is used to get a key.
V getValue() TIt is used to get a value.
int hashCode() It is used to get hashCode.
V setValue(V value) It will replace the value corresponding to this entry with the specified value.
boolean equals(Object o) It will compare the specified object with the other existing objects.
static <K extends Comparable<? super K>,V> Comparator<Map.Entry<K,V>> comparingByKey() It will get a comparator that compares the objects in natural order on key.
static <K,V> Comparator<Map.Entry<K,V>> comparingByKey(Comparator<? super K> cmp) It will get a comparator that compares the objects by key using the given Comparator.
static <K,V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() It will get a comparator that compares the objects in natural order on value.
static <K,V> Comparator<Map.Entry<K,V>> comparingByValue(Comparator<? super V> cmp) It will get a comparator that compares the objects by value using the given Comparator.

Java Map Example: Non-Generic:

import java.util.*;  
public class JavaMapExample {  
public static void main(String[] args) {  
    Map map=new HashMap();  
    //Adding elements to map  
    map.put(1,"A");  
    map.put(3,"B");  
    map.put(6,"C");  
    map.put(8,"D");  
    //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());  
    }  
}  
}

Output:

Java Map Example: Generic:

import java.util.*;  
public class JavaMapExample {  
 public static void main(String args[]){  
  Map<Integer,String> map=new HashMap<Integer,String>();  
  map.put(2,"A");  
  map.put(4,"B");  
  map.put(6,"C");  
  //Elements can traverse in any order  
  for(Map.Entry m:map.entrySet()){  
   System.out.println(m.getKey()+" "+m.getValue());  
  }  
 }  
}

Output:

Java Map Example: comparingByKey():

import java.util.*;  
public class JavaMapExample {  
 public static void main(String args[]){  
Map<Integer,String> map=new HashMap<Integer,String>();          
      map.put(10,"a");    
      map.put(20,"b");    
      map.put(30,"c");   
      //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);  
 }  
}

Output:

Java Map Example: comparingByKey() in Descending Order:

import java.util.*;  
public class JavaMapExample {  
 public static void main(String args[]){  
Map<Integer,String> map=new HashMap<Integer,String>();          
      map.put(2,"aa");    
      map.put(3,"bb");    
      map.put(5,"cc");    
      //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);  
 }  
}

Output:

Java Map Example: comparingByValue():

import java.util.*;  
public class JavaMapExample {  
 public static void main(String args[]){  
Map<Integer,String> map=new HashMap<Integer,String>();          
      map.put(11,"AA");    
      map.put(22,"CC");    
      map.put(33,"EE");    
      //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);  
 }  
}

Output:

Java Map Example: comparingByValue() in Descending Order:

import java.util.*;  
class JavaMapExample {  
 public static void main(String args[]){  
Map<Integer,String> map=new HashMap<Integer,String>();          
      map.put(224,"AA");    
      map.put(222,"BB");    
      map.put(223,"CC");    
     //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);  
 }  
}

Output:

Next Topic: Daemon thread in java in java with example.
Previous Topic: List interface in java with example.

Please Share