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.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);
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);
}
}
The output of our code snippet is:
Items IN in order : one,two,three,four
Items OUT in order: four,three,two,one
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024