Java – Remove Item from Collection

It is tricky to remove items from a list while within a loop, this is due to the fact that the index and length of the list get changed.
It is a good idea to delete an item from List using Iterator interface remove() method. The same goal can be achieved using removeIf() option

 

package com.pwn.collection;

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

public class RmvItemFrmCollectoin {

	public static void main(String[] args) {
		List<String> cities = new ArrayList<String>();
		cities.add("San Francisco");
		cities.add("New York");
		cities.add("San Diego");
		System.out.println("Before deleting List " + cities);
		Iterator<String> citiesIterator = cities.iterator();
		while (citiesIterator.hasNext()) {
			String city = citiesIterator.next();

			if ("San Diego".equals(city)) {
				citiesIterator.remove();
			}
		}

		System.out.println("After deleting List " + cities);
		cities = new ArrayList<String>();
		cities.add("San Francisco");
		cities.add("New York");
		cities.add("San Diego");

		cities.removeIf(p -> "San Diego".equals(p));

		System.out.println("After deleting List " + cities);

	}

}
Before deleting List [San Francisco, New York, San Diego]
After deleting List [San Francisco, New York]
After deleting List [San Francisco, New York]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s