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<>();
        deque.add("one");
        deque.add("two");
        deque.add("three");
        deque.add("four");

        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.append(s).append(",");
        }

        in.deleteCharAt(in.length() - 1);
        System.out.println(in.toString());

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

            // Retrieves and removes the last element of this deque,
            // or returns null if this deque is empty.
            deque.pollLast();
        }

        out.deleteCharAt(out.length() - 1);
        System.out.println(out.toString());
    }
}

The output of our code snippet is:

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

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

Leave a Reply