Java LinkedList removeFirstOccurrence(Object o) Method Example

The remove(Object o) method of java.util.LinkedList class which removes the first occurrence of the element from the list if it is present. If the element is not present then it leaves the list untouched. Same way removeFirstOccurrence(Object o) removes the first occurrence of the specified element in this list, when traversing the list from head to tail.

Signature

public boolean removeFirstOccurrence(Object o)

This method removes the first occurrence of the element of the list and returns true if the removal was successful.

Example

The following example shows the usage of java.util.LinkedList.removeFirstOccurrence(o) method.

import java.util.LinkedList;

public class RemoveFirstOccurrenceLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the list
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list before removeFirstOccurrence**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		//Removing the "Element1" from the list
		boolean flag = l.removeFirstOccurrence("Element1");
		System.out.println("Is the removal successful ?? "+flag);
		
		//Printing the elements of the list
		System.out.println("**Elements of the list after removeFirstOccurrence**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

**Elements of the list before removeFirstOccurrence**
Element1
Element2
Element3
Is the removal successful ?? true
**Elements of the list after removeFirstOccurrence**
Element2
Element3

Leave a Reply

Your email address will not be published. Required fields are marked *