w3resource

Java ArrayDeque Class: removeFirstOccurrence() Method

public boolean removeFirstOccurrence(Object o)

The removeFirstOccurrence() method is used to remove the first occurrence of an specified element in a given deque (when traversing the deque from head to tail). If the deque does not contain the element, it is unchanged. More formally, removes the first element e such that o.equals(e) (if such an element exists).

Package: java.util

Java Platform: Java SE 8

Syntax:

removeFirstOccurrence(Object o)

Parameters:

Name Description
o element to be removed from this deque, if present

Return Value:

true if the deque contained the specified element

Return Value Type: boolean

Pictorial Presentation

Java ArrayDeque Class: removeFirstOccurrence() Method

Example: Java ArrayDeque Class: removeFirstOccurrence() Method

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
   public static void main(String[] args) {
      
      // Create an array deque 
      Deque<Integer> deque = new ArrayDeque<Integer>(8);

      // Use add() method to add elements in the deque
      deque.add(100);
      deque.add(200);
      deque.add(150);
      deque.add(95);  
      deque.add(200); 

      // Print all the elements of the original deque
      System.out.println("Elements of the original deque:");
      for (Integer number : deque) {
         System.out.println("Number = " + number);
      }

     // removeFirstOccurrence() will remove first occurrence of element 200
      deque.removeFirstOccurrence(200);


      // Print all the elements available in deque
      System.out.println("New deque:");
      for (Integer number : deque) {
         System.out.println("Number = " + number);
      }
   }
}

Output:

Elements of the original deque:
Number = 100
Number = 200
Number = 150
Number = 95
Number = 200
New deque:
Number = 100
Number = 150
Number = 95
Number = 200

Java Code Editor:

Previous:removeFirst Method
Next:removeLast Method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-tutorial/util/arraydeque/java_arraydeque_removefirstoccurrence.php