Remove an Entry using key from HashMap while Iterating over it
Given a HashMap and a key in Java, the task is to remove an entry from this HashMap using the key, while iterating over it.
Examples:
Input: HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}, key = 2
Output: {1=Geeks, 3=GeeksForGeeks}
Input: HashMap: {1=G, 2=e, 3=e, 4=k, 5=s}, key = 3
Output: {1=G, 2=e, 4=k, 5=s}
- Using Java 7 and before:
- Get the HashMap and the Key
- Create an iterator to iterate over the HashMap using HashMap.iterate() method.
- Iterate over the HashMap using the Iterator.hasNext() method.
- While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.
- If the key matches, remove the entry of that iteration from the HashMap using remove() method.
- The required entry has been successfully removed.
Program:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<Integer, String>
map = new HashMap<>();
map.put( 1 , "Geeks" );
map.put( 2 , "ForGeeks" );
map.put( 3 , "GeeksForGeeks" );
int keyToBeRemoved = 2 ;
System.out.println( "Original HashMap: "
+ map);
Iterator<Map.Entry<Integer, String> >
iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String>
entry
= iterator.next();
if (keyToBeRemoved == entry.getKey()) {
iterator.remove();
}
}
System.out.println( "Modified HashMap: "
+ map);
}
}
|
Output:
Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}
Modified HashMap: {1=Geeks, 3=GeeksForGeeks}
- Using Java 8 lambda expressions:
- Get the HashMap and the Key
- Get the entry set of this map using HashMap.entrySet() method.
- Using lambda expression, remove the entry from the map if the key is equal to the key specified. The entry key of the Map can be obtained with the help of entry.getKey() method.
- The required entry has been successfully removed.
Program:
import java.util.*;
public class GFG {
public static void main(String[] args)
{
HashMap<Integer, String>
map = new HashMap<>();
map.put( 1 , "Geeks" );
map.put( 2 , "ForGeeks" );
map.put( 3 , "GeeksForGeeks" );
int keyToBeRemoved = 2 ;
System.out.println( "Original HashMap: "
+ map);
map.entrySet()
.removeIf(
entry -> (keyToBeRemoved == entry.getKey()));
System.out.println( "Modified HashMap: "
+ map);
}
}
|
Output:
Original HashMap: {1=Geeks, 2=ForGeeks, 3=GeeksForGeeks}
Modified HashMap: {1=Geeks, 3=GeeksForGeeks}
Last Updated :
11 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...