Thursday, 10 December 2015

How to Remove Element from Collection Using Iterator ?

package com.JavaInterview.Programs;

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

/**
 * Remove Element from Collection Using Iterator
 * 
 * 
 */
public class RemoveElementItrJIP {

 public static void main(String args[]) {
  List<String> JipList = new ArrayList<String>();
  JipList.add("ABC");
  JipList.add("Ram");
  JipList.add("DEF");
  JipList.add("123");
  System.out.println("The original Collection " + JipList);
  Iterator<String> itr = JipList.iterator();
  int count = 0;
  Scanner input = new Scanner(System.in);
  System.out.println("Please enter the element that you want to Remove :");
  String rmvElement = input.next();
  while (itr.hasNext()) {
   if (rmvElement.equals(itr.next())) {
    itr.remove();
    count++;
   }
  }

  if (count > 0) {
   System.out.println("After Remove:" + JipList);
  } else {
   System.out.println("No such element Exist!");

  }

  input.close();
 }
}

Output :
The original Collection [ABC, Ram, DEF, 123]
Please enter the element that you want to Remove :
123
After Remove:[ABC, Ram, DEF]


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...