How do I add elements into a Deque?

To add elements into a Deque object we can use the add(), addFirst() and addLast() method call.

package org.kodejava.example.util;

import java.util.Deque;
import java.util.LinkedList;

public class DequeAddElement {
    public static void main(String[] args) {
        //
        // Create an instance of Deque using LinkedList class.
        //
        Deque deque = new LinkedList();
        
        //
        // Insert a word into the Deque
        //
        deque.add("jumps");

        //
        // Insert words at the beginning of the current Deque 
        // elements
        //
        deque.addFirst("fox");
        deque.addFirst("brown");
        deque.addFirst("quick");
        deque.addFirst("The");

        //
        // Insert words at the end of the current Deque elements
        //
        deque.addLast("over");
        deque.addLast("the");
        deque.addLast("lazy");
        deque.addLast("dog");

        for (String word : deque) {
            System.out.println("word = " + word);
        }
    }
}

Here is the output:

word = The
word = quick
word = brown
word = fox
word = jumps
word = over
word = the
word = lazy
word = dog
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply