JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Program: How to remove an element from collection using Iterator object?


Description:

Below example shows how to remove an element from collection object using Iterator object. The remove() method removes from the underlying collection the last element returned by the iterator


Code:
package com.java2novice.iterator;

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

public class MyItrRemoveElement {

	public static void main(String a[]){
		
		String removeElem = "Perl";
		List<String> myList = new ArrayList<String>();
		myList.add("Java");
		myList.add("Unix");
		myList.add("Oracle");
		myList.add("C++");
		myList.add("Perl");
		System.out.println("Before remove:");
		System.out.println(myList);
		Iterator<String> itr = myList.iterator();
		while(itr.hasNext()){
			if(removeElem.equals(itr.next())){
				itr.remove();
			}
		}
		System.out.println("After remove:");
		System.out.println(myList);
	}
}

Output:
Before remove:
[Java, Unix, Oracle, C++, Perl]
After remove:
[Java, Unix, Oracle, C++]
<< Previous Program 

List Of Iterator Sample Programs:

  1. How to iterate through collection objects?
  2. How to remove an element from collection using Iterator object?
Knowledge Centre
String Vs StringBuffer
We know that String is immutable object. We can not change the value of a String object once it is initiated. If we try to change the value of the existing String object then it creates new object rather than changing the value of the existing object. So incase, we are going to do more modificatios on String, then use StringBuffer. StringBuffer updates the existing objects value, rather creating new object.
Famous Quotations
Before you go and criticize the younger generation, just remember who raised them.
-- Unknown Author

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.