LinkedList removeFirstOccurrence() Method in Java
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
import java.util.LinkedList;
public class GfG {
public static void main(String[] args)
{
LinkedList<String> list = new LinkedList<String>();
list.addLast( "one" );
list.addLast( "two" );
list.addLast( "three" );
list.addLast( "one" );
System.out.print( "List before removing the " +
"first Occurrence of \"one\" : " );
System.out.println(list);
boolean returnValue = list.removeFirstOccurrence( "one" );
System.out.println( "Returned Value : " + returnValue);
System.out.print( "List after removing the" +
" first Occurrence of \"one\" : " );
System.out.println(list);
}
}
|
Output:
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
import java.util.LinkedList;
public class GfG {
public static void main(String[] args)
{
LinkedList<Integer> list = new LinkedList<Integer>();
list.addLast( 10 );
list.addLast( 20 );
list.addLast( 30 );
list.addLast( 10 );
System.out.print( "List before removing the" +
" first Occurrence of \"10\" : " );
System.out.println(list);
boolean returnValue = list.removeFirstOccurrence( 10 );
System.out.println( "Returned Value : " + returnValue);
System.out.print( "List after removing the" +
" first Occurrence of \"10\" : " );
System.out.println(list);
}
}
|
Output:
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]
Last Updated :
30 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...