Monday 27 May 2019

Java: Delete elements of list while iterating


Using ‘iterator’, you can delete elements of list while iterating.

public static void printAndDeleteElements(List<?> list) {
         Iterator<?> iter = list.iterator();

         while (iter.hasNext()) {
                  Object element = iter.next();
                  System.out.println(element);
                  iter.remove();
         }

}

App.java
package com.sample.app;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class App {

 public static void printAndDeleteElements(List<?> list) {
  Iterator<?> iter = list.iterator();

  while (iter.hasNext()) {
   Object element = iter.next();
   System.out.println(element);
   iter.remove();
  }

 }

 public static void main(String args[]) {
  List<String> hobbies = new ArrayList<>();
  hobbies.add("chess");
  hobbies.add("cricket");
  hobbies.add("tennis");

  System.out.println("Number of hobbies : " + hobbies.size() + "\n");
  printAndDeleteElements(hobbies);
  System.out.println("\nNumber of hobbies : " + hobbies.size());

 }

}

Output
Number of hobbies : 3

chess
cricket
tennis

Number of hobbies : 0


You may like

No comments:

Post a Comment