The java.util.LinkedList.removeFirstOccurrence() is used to remove the first occurrence of the specified element from the list. If there is no occurrence of the specified element the list remains unchanged.
Syntax:
LinkedListObject.removeFirstOccurrence(Object element)
Parameters: The method takes one parameter element which is to be removed from the list. The type Object should be the same as the elements in the list.
Return Value: The method returns boolean True if the list contains the specified element and is deleted, otherwise it returns false.
Below programs illustrate the removeFirstOccurrence() method:
Program 1 :
// Java code to demonstrate removeFirstOccurrence() method import java.util.LinkedList;
public class GfG {
// Main method
public static void main(String[] args)
{
// Creating a LinkedList object
LinkedList<String> list = new LinkedList<String>();
// Adding an element at the last
list.addLast( "one" );
// Adding an element at the last
list.addLast( "two" );
// Adding an element at the last
list.addLast( "three" );
// Adding an element at the last
list.addLast( "one" );
System.out.print( "List before removing the " +
"first Occurrence of \"one\" : " );
// Printing the list
System.out.println(list);
// Removing first occurrence of one.
boolean returnValue = list.removeFirstOccurrence( "one" );
// Printing the returned value
System.out.println( "Returned Value : " + returnValue);
System.out.print( "List after removing the" +
" first Occurrence of \"one\" : " );
// Printing the list
System.out.println(list);
}
} |
List before removing the first Occurrence of "one" : [one, two, three, one] Returned Value : true List after removing the first Occurrence of "one" : [two, three, one]
Program 2 :
// Java code to demonstrate removeFirstOccurrence method in LinkedList import java.util.LinkedList;
public class GfG {
// Main method
public static void main(String[] args)
{
// Creating a LinkedList object
LinkedList<Integer> list = new LinkedList<Integer>();
// Adding an element at the last
list.addLast( 10 );
// Adding an element at the last
list.addLast( 20 );
// Adding an element at the last
list.addLast( 30 );
// Adding an element at the last
list.addLast( 10 );
System.out.print( "List before removing the" +
" first Occurrence of \"10\" : " );
// Printing the list
System.out.println(list);
// Removing first occurrence of one.
boolean returnValue = list.removeFirstOccurrence( 10 );
// Printing the returned value
System.out.println( "Returned Value : " + returnValue);
System.out.print( "List after removing the" +
" first Occurrence of \"10\" : " );
// Printing the list
System.out.println(list);
}
} |
List before removing the first Occurrence of "10" : [10, 20, 30, 10] Returned Value : true List after removing the first Occurrence of "10" : [20, 30, 10]