Monday, 20 January 2020

Remove elements of map while iterating?


Approach 1: Using iterator
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();

while (iterator.hasNext()) {
 iterator.remove();
}


App.java
package com.sample.app;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class App {

 public static void main(String[] args) {
  Map<Integer, String> map = new HashMap<>();

  map.put(1, "Krishna");
  map.put(2, "Ram");
  map.put(3, "Rahim");
  map.put(4, "Joel");

  System.out.println(map);

  System.out.println("Deleting all the entries in map whose key is even number");
  Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();

  while (iterator.hasNext()) {
   int key = iterator.next().getKey();

   if (key % 2 == 0) {
    iterator.remove();
   }
  }

  System.out.println(map);

 }

}

Output
{1=Krishna, 2=Ram, 3=Rahim, 4=Joel}
Deleting all the entries in map whose key is even number
{1=Krishna, 3=Rahim}

Approach 2: Use removeIf function
‘removeIf’ function is added in Java8.

Example
map.entrySet().removeIf(entry -> entry.getKey() % 2 == 0);


App.java
package com.sample.app;

import java.util.HashMap;
import java.util.Map;

public class App {

 public static void main(String[] args) {
  Map<Integer, String> map = new HashMap<>();

  map.put(1, "Krishna");
  map.put(2, "Ram");
  map.put(3, "Rahim");
  map.put(4, "Joel");

  System.out.println(map);

  System.out.println("Deleting all the entries in map whose key is even number");

  map.entrySet().removeIf(entry -> entry.getKey() % 2 == 0);

  System.out.println(map);

 }

}

Output
{1=Krishna, 2=Ram, 3=Rahim, 4=Joel}
Deleting all the entries in map whose key is even number

{1=Krishna, 3=Rahim}


You may like

No comments:

Post a Comment