How do I create a Last-In-First-Out Deque?

This example show you how to create a LIFO (Last In First Out) Deque. We call the Deque.peekLast() method to get the last element from the Deque, poll the last element and repeat until all the elements read.

package org.kodejava.example.util;

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

public class DequeLifoDemo {

    public static void main(String[] args) {
        // Create an instance of a Deque, here we use the LinkedList
        // class which implements the Deque interface.
        Deque<String> deque = new LinkedList<>();

        StringBuilder in = new StringBuilder("Items IN in order : ");

        // Returns an iterator over the elements in this deque in
        // proper sequence
        for (String s : deque) {

        in.deleteCharAt(in.length() - 1);

        StringBuilder out = new StringBuilder("Items OUT in order: ");
        for (int i = 0; i < deque.size();) {

            // Retrieves and removes the last element of this deque,
            // or returns null if this deque is empty.

        out.deleteCharAt(out.length() - 1);

The output of our code snippet is:

Items IN in order : one,two,three,four
Items OUT in order: four,three,two,one

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.