Tag Archives: Map.Entry

Java: Nested Interface


An interface declared within another interface or class is called a nested interface.

The nested interfaces in java are used to group related interfaces so that easily maintain. The nested interface can’t be accessed directly. For accessing must be referred to by the outer interface or class.

For example, the Nested interface is just like almirah inside the room, for accessing almirah, first need to enter the room.

In the java collection framework,  Entry is the subinterface of Map i.e. accessed by Map. Entry.

Points to remember for nested interfaces

  • Nested interfaces are declared static implicitly.
  • Nested interface can have any access modifier while inside the class but if use inside interface then it must be public.

Syntax of Nested Interface inside Class

class class_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}

Syntax of Nested Interface inside Interface

interface interface_name{  
 ...  
 interface nested_interface_name{  
  ...  
 }  
}  

Example of Nested Interface: Interface within Interface

interface Readable{
  void show();
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Interface

we are accessing the Message interface by its outer interface Readable because it cannot be accessed directly.

class NestedInterfaceExample1 implements Readable.Message{

 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
  //upcasting here
  Readable.Message message=new NestedInterfaceExample1();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Note: For the above example when you compile Readable class, compiler internally creates the public and static interface as given below:

public static interface Showable$Message
{
  public abstract void messageDetail();
}

As you can see in the above example, The java compiler internally creates the public and static interface.

Example of Nested Interface: Interface within Class

In the below example you will see, interface implementation inside the class and how can we access it.

class ClassA{
  interface Message{
   void messageDetail();
  }
}

Access of Nested Interface within Class

class NestedInterfaceExample2 implements ClassA.Message{
 public void messageDetail(){
 System.out.println("Hello !!! you are calling messageDetail method.");
 }  

 public static void main(String args[]){
 //upcasting here
  ClassA.Message message=new NestedInterfaceExample2();
  message.messageDetail();
 }
}

Output

Hello !!! you are calling messageDetail method.

Can we define a class inside the interface?

Yes, If we implement a class inside the interface, the java compiler automatically creates a static nested class. In this example you will see how can we define a class within the interface:

interface M{
class A{}
}

 

Java: Map Interface Methods and Examples


In the collection framework, a map contains values on the basis of key and value pairs. This pair is known as an entry.

Points to Remember

  • Map contains unique keys.
  • Map allows duplicate values.
  • Map is useful to search, update or delete elements on the basis of a key.
  • Map is the root interface in the Map hierarchy for Collection Framework.
  • Map interface is extended by SortedMap and implemented by HashMap, LinkedHashMap.
  • Map implementation classes HashMap and LinkedHashMap allow null keys and values but TreeMap doesn’t allow null key and value.
  • Map can’t be traversed, for transversing needs to convert into the set using method keySet() or entrySet().

See Also:

Methods of Map Interface

Method Description
put(Object key, Object value) This method used to insert an entry on the map.
void putAll(Map map) This method inserts the specified map in the map.
V putIfAbsent(K key, V value) This method inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key) This method used to delete an entry for the specified key.
boolean remove(Object key, Object value) This method removes the specified values with the associated specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry> 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) This method computes 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) This method computes 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) This method computes 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)  if some value equal to the value exists within the map then return true, else return false.
boolean containsKey(Object key) if some key equal to the key exists within the map return true, else return false.
boolean equals(Object o) It is used to compare the specified Object values with the Map.
void forEach(BiConsumer action) Mentioned action will perform for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key) Returns the object that contains the value with respect to the key.
V getOrDefault(Object key, V defaultValue) Returns the value with respect to 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() Check if the map not having any element Returns true if the map is empty or false.
V merge(K key, V value, BiFunction remappingFunction) If the given key is not mapped with a value or with null, associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to the key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to the key.
void replaceAll(BiFunction function) It replaces each entry’s value with the given function on that entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() Returns the number of elements in the map.

Map.Entry Interface

Entry is the subinterface of Map. So we will be accessed by Map.Entry name. It returns a collection-view of the map, whose elements are of this class. It provides methods to get key and value.

Methods of Map.Entry interface

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<Map.Entry> comparingByKey() It returns a comparator that compare the objects in natural order on key.
static Comparator<Map.Entry> comparingByKey(Comparator cmp) It returns a comparator that compare the objects by key using the given Comparator.
static <K,V extends Comparable> Comparator<Map.Entry> comparingByValue() It returns a comparator that compare the objects in natural order on value.
static Comparator<Map.Entry> comparingByValue(Comparator cmp) It returns a comparator that compare the objects by value using the given Comparator.

Map Example: Legacy Style without Generics

import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
    Map map=new HashMap();
    //Adding elements to map
    map.put(1,"Anuj");
    map.put(5,"Raghav");
    map.put(2,"Jitendra");
    map.put(3,"Anuj");
    //Traversing Map Entry
	//Converting to Set so that we can traverse
    Set set=map.entrySet();
    Iterator itr=set.iterator();
    while(itr.hasNext()){
        //Type cast 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 :


1 Anuj
2 Jitendra
5 Raghav
3 Anuj

Map Example: With Generics

import java.util.*;
class MapExample2{
 public static void main(String args[]){
  Map map=new HashMap();
  map.put(20,"Anuj");
  map.put(21,"Virendra");
  map.put(22,"Raghav");
  //Elements can traverse in any order
  for(Map.Entry m:map.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }
}

Output :


22 Raghav
20 Anuj
21 Virendra

Map Example: comparingByKey() in ascending and descending order

import java.util.*;
class MapExample3{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav"); 

	  //ascending order
      //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);  

	  //descending oder
	  //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 :


20=Anuj
21=Virendra
22=Raghav

Map Example: comparingByValue() in ascending and descending Order

import java.uti
class MapExample5{
 public static void main(String args[]){
Map map=new HashMap();
      map.put(20,"Anuj");
      map.put(21,"Virendra");
      map.put(22,"Raghav");  

	  //ascending order 

      //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);  

	  //descending order

	  //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 :


20=Anuj
22=Raghav
21=Virendra

21=Virendra
22=Raghav
20=Anuj

Java: TreeMap Class Methods and Examples


Java.util.TreeMap implements SortedMap interface and provides an efficient way to storing key-value pairs in sorted order. TreeMap implements the NavigableMap interface and extends AbstractMap class.

Points to Remember

  • TreeMap uses data structure as a red-black tree.
  • TreeMap contains values based on the key.
  • TreeMap contains only unique elements.
  • TreeMap cannot have a null key but can have multiple null values.
  • TreeMap is not synchronized.
  • TreeMap maintains an ascending order.

TreeMap Declaration

public class TreeMap extends AbstractMap implements NavigableMap, Serializable,Cloneable
  • K: Represent as key in Map
  • V: Represent as value with respect to K.

See Also:

What is the difference between HashMap and TreeMap?

HashMap TreeMap
HashMap can contain one null key. TreeMap cannot contain any null key.
HashMap maintains no order. TreeMap maintains an ascending order.

Constructors of TreeMap

Constructor Description
TreeMap() This constructor uses to create an empty treemap that will be sorted using the natural order of its key.
TreeMap(Comparator comparator) This constructor uses to an empty tree-based map that will be sorted using the comparator comp.
TreeMap(Map m) It is used to initialize a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap m) This constructor uses to initialize a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

Methods of TreeMap

Method Description
Map.Entry ceilingEntry(K key) It returns the key-value pair having the least key, greater than or equal to the specified key, or null if there is no such key.
K ceilingKey(K key) It returns the least key, greater than the specified key or null if there is no such key.
void clear() It removes all the key-value pairs from a map.
Object clone() It returns a shallow copy of TreeMap instance.
Comparator comparator() It returns the comparator that arranges the key in order, or null if the map uses the natural ordering.
NavigableSet descendingKeySet() This method returns a reverse order NavigableSet view of the keys contained in the map.
NavigableMap descendingMap() It returns the specified key-value pairs in descending order.
Map.Entry firstEntry() It returns the key-value pair having the least key.
Map.Entry floorEntry(K key) It returns the greatest key, less than or equal to the specified key, or null if there is no such key.
void forEach(BiConsumer action) It performs the mention action for each entry in the map until all entries processed or the action throws an exception.
SortedMap headMap(K toKey) It returns the key-value pairs whose keys are strictly less than toKey.
NavigableMap headMap(K toKey, boolean inclusive) It returns the key-value pairs whose keys are less than (or equal to if inclusive is true) toKey.
Map.Entry higherEntry(K key) It returns the least key strictly greater than the given key, or null if there is no such key.
K higherKey(K key) It is used to return true if map contains a mapping for the specified key.
Set keySet() It returns the set of keys exist in the map.
Map.Entry lastEntry() It returns the key-value pair having the greatest key, or null if there is no such key.
Map.Entry lowerEntry(K key) It returns a key and value mapping associated with the greatest key less than the given key or null if there is no such key.
K lowerKey(K key) It returns from map  the greatest key strictly less than the given key, or null if there is no such key.
NavigableSet navigableKeySet() It returns a NavigableSet view of the keys contains in this map.
Map.Entry pollFirstEntry() It removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
Map.Entry pollLastEntry() It removes and returns a key and value mapping associated with the greatest key in this map, or null if the map is empty.
V put(K key, V value) It inserts the specified value with respect to key in the map.
void putAll(Map map) It is used to copy all the key-value pair from one map to another map.
V replace(K key, V value) It replaces the value with respect to key.
boolean replace(K key, V oldValue, V newValue) It replaces the old value with the new value with respect to key.
void replaceAll(BiFunction function) It replaces each entry’s value with the result of invoking the mentioned function on all entries have been processed or the function throw an exception.
NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) It returns key and value pairs whose keys match with in range fromKey to toKey.
SortedMap subMap(K fromKey, K toKey) It returns key and value pairs whose keys range match fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap(K fromKey) It returns key and value pairs whose keys are greater than or equal to fromKey.
NavigableMap tailMap(K fromKey, boolean inclusive) It returns key and value pairs whose keys are greater than (o equal to, if inclusive is true) fromKey.
boolean containsKey(Object key) It returns true if the map contains a mapping with respect to  key.
boolean containsValue(Object value) It returns true if the map find one or more keys to the specified value.
K firstKey() It is used to return the first find lowest key currently in this sorted map.
V get(Object key) It is used to return the value to which the map maps the specified key.
K lastKey() It is used to return the last highest key currently in the sorted map.
V remove(Object key) It removes the key and value pair of the specified key from the map.
Set entrySet() It returns a set of the mappings contained in the map.
int size() It returns the number of key-value pairs that exists in the hashtable.
Collection values() It returns a collection  of values contained in the map.

TreeMap Example : insert and traverse elements

import java.util.Map;
import java.util.TreeMap;

class TreeMapExample1{
	 public static void main(String args[]){
	   TreeMap&lt;Integer,String&gt; map=new TreeMap&lt;Integer,String&gt;();
	      map.put(20,"Anuj");
	      map.put(22,"Ravi");
	      map.put(21,"Virendra");
	      map.put(23,"Raghav");    

	      for(Map.Entry m:map.entrySet()){
	       System.out.println(m.getKey()+" "+m.getValue());
	      }
	 }
	}

Output :


20 Anuj
21 Virendra
22 Ravi
23 Raghav

TreeMap Example : remove() elements

import java.util.*;

public class TreeMapExample2 {
	public static void main(String args[]) {
		TreeMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		System.out.println("\nBefore invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		map.remove(22);
		System.out.println("\nAfter invoking remove() method");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :



Before invoking remove() method
20 Anuj
21 Virendra
22 Ravi
23 Raghav

After invoking remove() method
20 Anuj
21 Virendra
23 Raghav

Treemap Example : with NavigableMap

import java.util.*;
import java.util.NavigableMap;
import java.util.TreeMap;

class TreeMapExample3 {
	public static void main(String args[]) {
		NavigableMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");

		// Maintains descending order
		System.out.println("\ndescendingMap: " + map.descendingMap());
		// Returns key-value pairs whose keys are less than or equal to the
		// specified key.
		System.out.println("\nheadMap: " + map.headMap(22, true));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22, true));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, false, 22, true));
	}
}

Output :


descendingMap: {23=Raghav, 22=Ravi, 21=Virendra, 20=Anuj}

headMap: {20=Anuj, 21=Virendra, 22=Ravi}

tailMap: {22=Ravi, 23=Raghav}

subMap: {21=Virendra, 22=Ravi}

TreeMap Example : SortedMap()

import java.util.*;
import java.util.SortedMap;
import java.util.TreeMap;

class TreeMapExample4 {
	public static void main(String args[]) {
		SortedMap&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();
		map.put(20, "Anuj");
		map.put(22, "Ravi");
		map.put(21, "Virendra");
		map.put(23, "Raghav");
		// Returns key-value pairs whose keys are less than the specified key.
		System.out.println("\nheadMap: " + map.headMap(22));
		// Returns key-value pairs whose keys are greater than or equal to the
		// specified key.
		System.out.println("\ntailMap: " + map.tailMap(22));
		// Returns key-value pairs exists in between the specified key.
		System.out.println("\nsubMap: " + map.subMap(20, 22));
	}
}

Output :


headMap: {20=Anuj, 21=Virendra}

tailMap: {22=Ravi, 23=Raghav}

subMap: {20=Anuj, 21=Virendra}

TreeMap Example : with objects

import java.util.*;
class Magzine{
int id;
String name,author,publisher;
int quantity;
public Magzine(int id, String name, String author, String publisher, int quantity) {
    this.id = id;
    this.name = name;
    this.author = author;
    this.publisher = publisher;
    this.quantity = quantity;
}
}
import java.util.Map;
import java.util.TreeMap;

public class HashtableExampleWithObjects {
	public static void main(String[] args) {
		// Creating map of Magzine
		Map&lt;Integer, Magzine&gt; table = new TreeMap&lt;Integer, Magzine&gt;();
		// Creating Magzines
		Magzine m1 = new Magzine(21, "The Sun", "Sy Sunfranchy", "The Sun Company", 8);
		Magzine m2 = new Magzine(22, "Glimmer Trains", "Unknown", "Glimmer Train Press", 4);
		Magzine m3 = new Magzine(23, "Crazy horse", "Brett Lot", "College of Charleston", 6);

		// Adding magzine to map
		table.put(1, m1);
		table.put(2, m2);
		table.put(3, m3);
		// Traversing map
		for (Map.Entry&lt;Integer, Magzine&gt; entry : table.entrySet()) {
			int key = entry.getKey();
			Magzine m = entry.getValue();
			System.out.println("\nId: "+key + " Details:");
			System.out.println(m.id + " " + m.name + " " + m.author + " " + m.publisher + " " + m.quantity);
		}
	}
}

Output :


Id: 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Id: 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Id: 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

 

Java: HashMap Class Methods and Examples


java.util.HashMap class inherits AbstractMap class and implements the Map interface. HashMap values store on the basis of key and value pair where each pair is known as an Entry.

  • K: It’s the type of Key in HashMap
  • V: It’s a type of value with respect to Key.

HashMap Class Declaration


public class HashMap extends implements Map, Cloneable, Serializable  

See Also:

Points to Remember:

  • HashMap uses data structure as a Hash Table.
  • HashMap store values based on keys.
  • HashMap contains unique keys.
  • HashMap allows duplicate values.
  • HashMap doesn’t maintain order.
  • HashMap class allows only one null key and multiple null values.
  • HashMap is not synchronized.
  • HashMap initial default capacity is 16 elements with a load factor of 0.75.

HashMap Representataion

Difference between HashSet and HashMap

HashSet Class contains only values whereas HashMap Class contains an entry (key and value pair).

HashMap Class Constructors

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor) It is used to initialize both the capacity and load factor of the hash map by using its arguments.

HashMap Class Methods

Method Description
void clear() Use to remove all of the mappings from this map.
boolean isEmpty() Use to return true if this map contains no key-value mappings.
Object clone() Use to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet() Use to return a collection view of the mappings contained in this map.
Set keySet() Use to return a set view of the keys contained in this map.
V put(Object key, Object value) Use to insert an entry in the map.
void putAll(Map map) Use to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value in the map only when  specified key is not already specified.
V remove(Object key) Use to delete an entry for the specified key.
boolean remove(Object key, Object value) removes the  values with the associated specified keys from the map.
V compute(K key, BiFunction remappingFunction) Use 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) Use to compute its value using the given mapping function, if the specified key is not mapped with a value or null, and enters it into this map unless null.
V computeIfPresent(K key, BiFunction remappingFunction) Use 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) It returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key) It returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o) Use to compare the specified Object with the Map.
void forEach(BiConsumer action) Added in Java 8 to  performs the given action for each entry in the map  or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated with respect to key.
V getOrDefault(Object key, V defaultValue) Added in Java 8. It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty() It 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 then associates it with the given non-null value.
V replace(K key, V value) It replaces the specified value with respect to specified key.
boolean replace(K key, V oldValue, V newValue) Replaces the old value with the new value with respect to specified key.
void replaceAll(BiFunction function) It replaces each entry’s value with entry until all entries have been processed or the function throws an exception.
Collection values() It returns a collection of the values contained in the map.
int size() It returns the count of number of entries in the map.

Example: add elements

Here, you will learn different ways to insert elements.

import java.util.*;

class HashMapExample1 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		System.out.println("Initial hash map elements: " + hm );
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");

		System.out.println("\nAfter invoking put() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}

		hm.putIfAbsent(23, "Gaurav");
		System.out.println("\nAfter invoking putIfAbsent() method");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		HashMap map = new HashMap();
		map.put(24, "Ravi");
		map.putAll(hm);
		System.out.println("\nAfter invoking putAll() method ");
		for (Map.Entry m : map.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements: {}

After invoking put() method
20 Anuj
21 Virendra
22 Raghav

After invoking putIfAbsent() method
20 Anuj
21 Virendra
22 Raghav
23 Gaurav

After invoking putAll() method 
20 Anuj
21 Virendra
22 Raghav
23 Gaurav
24 Ravi

HashMap Example : remove()

Here you will see different ways to remove elements from HashMap

import java.util.*;
import java.util.HashMap;

public class HashMapExample2 {
	public static void main(String args[]) {
		HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(20, "Anuj");
		map.put(21, "Virendra");
		map.put(22, "Raghav");
		map.put(23, "Gaurav");
		System.out.println("Initial hash map elements: " + map);
		// key-based removal
		map.remove(20);
		System.out.println("\nUpdated hash map  elements: " + map);
		// value-based removal
		map.remove(21);
		System.out.println("\nUpdated hash map  elements: " + map);
		// key-value pair based removal
		map.remove(22, "Raghav");
		System.out.println("\nUpdated hash map  elements: " + map);
	}
}

Output :


Initial hash map elements: {20=Anuj, 21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {21=Virendra, 22=Raghav, 23=Gaurav}

Updated hash map  elements: {22=Raghav, 23=Gaurav}

Updated hash map  elements: {23=Gaurav}

HashMap Example : replace()

Here you will see different ways to replace() elements in HashMap

import java.util.*;

class HashMapExample3 {
	public static void main(String args[]) {
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(20, "Anuj");
		hm.put(21, "Virendra");
		hm.put(22, "Raghav");
		System.out.println("Initial hash map elements:");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(22, "Gaurav");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replace(21, "Virendra", "Ravi");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
		System.out.println("\nUpdated hash map elements:");
		hm.replaceAll((k, v) -> "Anuj");
		for (Map.Entry m : hm.entrySet()) {
			System.out.println(m.getKey() + " " + m.getValue());
		}
	}
}

Output :


Initial hash map elements:
20 Anuj
21 Virendra
22 Raghav

Updated hash map elements:
20 Anuj
21 Virendra
22 Gaurav

Updated hash map elements:
20 Anuj
21 Ravi
22 Gaurav

Updated hash map elements:
20 Anuj
21 Anuj
22 Anuj

HashMap Example: Objects handling

import java.util.*;
public class Magzine {
	int id;
	String name,author,publisher;
	int quantity;
	public Magzine(int id, String name, String author, String publisher, int quantity) {
	    this.id = id;
	    this.name = name;
	    this.author = author;
	    this.publisher = publisher;
	    this.quantity = quantity;
	}    

}
public class MapExample {
import java.util.HashMap;
import java.util.Map;

public class HashMapWithObjectsExample {

	public static void main(String[] args) {
	    //Creating map of Magzines
	    Map<Integer,Magzine> map=new HashMap<Integer,Magzine>();
	    //Creating Books
	    Magzine m1=new Magzine(21,"The Sun","Sy Sunfranchy","The Sun Company",8);
	    Magzine m2=new Magzine(22,"Glimmer Trains","Unknown","Glimmer Train Press",4);
	    Magzine m3=new Magzine(23,"Crazy horse","Brett Lot","College of Charleston",6);
	    //Adding Magzines to map
	    map.put(1,m1);
	    map.put(2,m2);
	    map.put(3,m3);  

	    //Traversing map
	    for(Map.Entry<Integer,Magzine> entry:map.entrySet()){
	        int key=entry.getKey();
	        Magzine m=entry.getValue();
	        System.out.println("\nMagzine "+key+" Details:");
	        System.out.println(m.id+" "+m.name+" "+m.author+" "+m.publisher+" "+m.quantity);
	    }
	}
}

Output :



Magzine 1 Details:
21 The Sun Sy Sunfranchy The Sun Company 8

Magzine 2 Details:
22 Glimmer Trains Unknown Glimmer Train Press 4

Magzine 3 Details:
23 Crazy horse Brett Lot College of Charleston 6

References