How to remove range of elements from LinkedList

package JavaLinkedListExample;

import java.util.LinkedList;
import java.util.Scanner;

/*
 * Here we will learn to remove range of elements from LinkedList
 */
public class RemoveRangeOfElements {

	public static void main(String[] args) {
		/**
		 * Constructs a new Scanner that produces values scanned from the
		 * specified input stream.(Used to take input from user)
		 */
		Scanner scanner = new Scanner(System.in);

		LinkedList<String> linkedList = new LinkedList<String>();
		LinkedList<String> linkedListRemove = new LinkedList<String>();

		String objInput;

		System.out.println("Insert the elements in List(Enter exit to quit)");
		objInput = scanner.next();

		/*
		 * equalsIgnoreCase method compares this String to another String,
		 * ignoring case considerations.
		 */
		while (!objInput.equalsIgnoreCase("exit")) {
			linkedList.add(objInput);
			objInput = scanner.next();
		}
		System.out.println("nElements in List");
		for (Object obj : linkedList)
			System.out.println(obj);
		System.out.println("nSize of the list:" + linkedList.size());

		System.out
				.println("Insert the elements to remove from above List(Enter exit to quit)");
		objInput = scanner.next();
		while (!objInput.equalsIgnoreCase("exit")) {
			linkedListRemove.add(objInput);
			objInput = scanner.next();
		}

		System.out.println("Removing the element");

		/*
		 * removeAll(Collection<?> c) method iterates over this collection,
		 * checking each element returned by the iterator in turn to see if it's
		 * contained in the specified collection. If it's so contained, it's
		 * removed from this collection with the iterator's remove method.
		 */
		linkedList.removeAll(linkedListRemove);
		System.out.println("Elements removed from list");
		System.out.println("Elements in List");
		for (Object obj : linkedList)
			System.out.println(obj);

		System.out.println("Size of the list after removing :"
				+ linkedList.size());

	}
}

 

By | 2012-09-25T03:19:01+00:00 September 25th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment