Showing posts with label Java Collections. Show all posts
Showing posts with label Java Collections. Show all posts

Java Queue & Deque — Explained with Simple Examples

 

Java Queue & Deque — Explained with Simple Examples

In Java, Queue and Deque are important data structures widely used in real-world systems like messaging, scheduling, caching, undo/redo, browser history, task execution, and more. They come from the java.util package and follow FIFO / LIFO styles of processing.


✅ 1. What is a Queue in Java?

A Queue stores elements in the order they arrive and processes them in the same order.

👉 Works on: FIFO (First In – First Out)
📦 Example in real life: People standing in a line at a ticket counter.

Queue Interface Hierarchy

Collection | ---> Queue

Common Queue Implementations in Java

ImplementationDescription
LinkedListSimple queue (FIFO)
PriorityQueueOrders elements by priority (NOT FIFO)
ArrayDequeFaster queue without capacity limit

🔹 Basic Queue Operations

MethodDescription
add(e) / offer(e)Insert element
remove() / poll()Remove head
element() / peek()View head

💡 Difference between add() & offer()

  • add() → throws exception if queue is full

  • offer() → returns false if queue is full


🧪 Example 1 — Simple Queue using LinkedList

import java.util.Queue; import java.util.LinkedList; public class SimpleQueueExample { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); queue.offer("A"); queue.offer("B"); queue.offer("C"); System.out.println("Queue: " + queue); System.out.println("Peek: " + queue.peek()); System.out.println("Removed: " + queue.poll()); System.out.println("After Removal: " + queue); } }

Output

Queue: [A, B, C] Peek: A Removed: A After Removal: [B, C]

🧪 Example 2 — PriorityQueue (NOT FIFO)

PriorityQueue orders elements by natural order or custom comparator.

import java.util.PriorityQueue; public class PriorityQueueExample { public static void main(String[] args) { PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.add(30); pq.add(5); pq.add(20); System.out.println(pq.poll()); System.out.println(pq.poll()); System.out.println(pq.poll()); } }

Output

5 20 30

👉 Smallest element gets highest priority.


🧪 Example 3 — Max Priority Queue

import java.util.*; public class MaxPriorityQueueExample { public static void main(String[] args) { PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Collections.reverseOrder()); maxPQ.add(10); maxPQ.add(50); maxPQ.add(30); while(!maxPQ.isEmpty()) { System.out.println(maxPQ.poll()); } } }

Output

50 30 10

✅ 2. What is a Deque in Java?

Deque = Double Ended Queue
You can insert and remove from BOTH ends.

👉 Works as:

  • Queue (FIFO)

  • Stack (LIFO)

Deque Interface Hierarchy

Collection | Deque

Common Deque Implementation

ImplementationDescription
ArrayDequeMost common + fastest
LinkedListAlso supports Deque

Deque Operations

Insert

Method
addFirst()
addLast()
offerFirst()
offerLast()

Remove

Method
pollFirst()
pollLast()
removeFirst()
removeLast()

Peek

Method
peekFirst()
peekLast()

🧪 Example 4 — Deque as Queue (FIFO)

import java.util.Deque; import java.util.ArrayDeque; public class DequeAsQueue { public static void main(String[] args) { Deque<String> dq = new ArrayDeque<>(); dq.offerLast("A"); dq.offerLast("B"); dq.offerLast("C"); System.out.println(dq); System.out.println("Removed: " + dq.pollFirst()); System.out.println(dq); } }

Output

[A, B, C] Removed: A [B, C]

🧪 Example 5 — Deque as Stack (LIFO)

import java.util.ArrayDeque; import java.util.Deque; public class DequeAsStack { public static void main(String[] args) { Deque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); System.out.println(stack); System.out.println("Popped: " + stack.pop()); System.out.println(stack); } }

Output

[30, 20, 10] Popped: 30 [20, 10]

👉 ArrayDeque is recommended instead of Stack class
because Stack is synchronized & slower.


Queue vs Deque — Quick Comparison

FeatureQueueDeque
OrderFIFOFIFO + LIFO
Insert EndsRear onlyBoth ends
Remove EndsFront onlyBoth ends
Common ImplLinkedList, PriorityQueueArrayDeque

When to Use What?

Use CaseBest Choice
Simple FIFO tasksQueue (LinkedList)
Priority-based processingPriorityQueue
Stack replacementDeque
Both stack + queue flexibilityArrayDeque

Conclusion

Java provides powerful Queue and Deque implementations that are widely used in real-world systems for task scheduling, background processing, messaging, caching, and more.

  • Use Queue when order matters (FIFO)

  • Use PriorityQueue when priority matters

  • Use Deque / ArrayDeque when you need both stack + queue behavior

Java ListIterator Example

The ListIterator interface is a special kind of iterator designed to iterate over lists. It provides functionality to iterates a list in both direction. Here is one example to iterate a list in reverse order using ListIterator.

Example

package mycollectiontest;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListIterator {

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("One");
list.add("Two");
list.add("Three");
list.add("Four");
list.add("Five");
// Iterator allows only one direction
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());

}
// ListIterator allows traversing both direction
java.util.ListIterator<String> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}

}

Output

One
Two
Three
Four
Five
Five
Four
Three
Two
One

How to sort list of objects with multiple attributes?

We can sort list of objects using Collections.sort(Collection c) or Collections.sort(Collection c,Comparator) based on compareTo,compare implementations. Some scenarios we need to sort objects based on multiple attributes. Here is one simple example to sort student objects based on the department, name and address using apache common api.

Create a Maven project and add below dependency.

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>

Create a pojo class (Student.java)

package com.test.vinod;

public class Student {
private String name;
private String address;
private String dept;

public Student(String dept, String name, String address) {
super();
this.dept = dept;
this.name = name;
this.address = address;
}

//getters and setters

@Override
public String toString() {
return dept + " " + name + " "
+ address;
}

}

StudentComparator.java

package com.test.vinod;

import java.util.Comparator;

import org.apache.commons.lang3.builder.CompareToBuilder;

public class StudentComparator implements Comparator<Student> {

public int compare(Student o1, Student o2) {
return new CompareToBuilder().append(o1.getDept(), o2.getDept())
.append(o1.getName(), o2.getName())
.append(o1.getAddress(), o2.getAddress()).toComparison();
}

}

Main class (StudentSort.java)

package com.test.vinod;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentSort {

public static void main(String[] args) {
Student s1 = new Student("Commerce", "Vinod", "Bangalore");
Student s2 = new Student("Electronics", "Ram", "Chennai");
Student s3 = new Student("Electronics", "Vinod", "Bangalore");
Student s4 = new Student("Commerce", "Nirmal", "Bombay");
Student s5 = new Student("Electronics", "Ashok", "Delhi");
Student s6 = new Student("Electronics", "Prem", "Agra");
Student s7 = new Student("Commerce", "Anoop", "Bangalore");
Student s8 = new Student("Electronics", "Santhosh", "Cochin");
Student s9 = new Student("Commerce", "Vinod", "Agra");

List<Student> studentList = new ArrayList<Student>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
studentList.add(s6);
studentList.add(s7);
studentList.add(s8);
studentList.add(s9);

System.out.println("Before sorting:");
for (Student st : studentList) {
System.out.println(st);
}
Collections.sort(studentList, new StudentComparator());

System.out.println("\n\nAfter sorting:");
for (Student st : studentList) {
System.out.println(st);
}

}

}

Output

Before sorting:
Commerce Vinod Bangalore
Electronics Ram Chennai
Electronics Vinod Bangalore
Commerce Nirmal Bombay
Electronics Ashok Delhi
Electronics Prem Agra
Commerce Anoop Bangalore
Electronics Santhosh Cochin
Commerce Vinod Agra

After sorting:
Commerce Anoop Bangalore
Commerce Nirmal Bombay
Commerce Vinod Agra
Commerce Vinod Bangalore
Electronics Ashok Delhi
Electronics Prem Agra
Electronics Ram Chennai
Electronics Santhosh Cochin
Electronics Vinod Bangalore

Thread safe implementation of Queue (ConcurrentLinkedQueue) Example

An unbounded thread-safe queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.

Example

package com.vinod.test;

import java.util.concurrent.ConcurrentLinkedQueue;

public class ConcurrentLinkedQueueExample {

    public static void main(String[] args) {
        ConcurrentLinkedQueue<String> orderQueue = new ConcurrentLinkedQueue<String>();
        orderQueue.add("order number 1");
        orderQueue.add("order number 2 premium");
        orderQueue.add("order number 3");
        orderQueue.add("order number 4");
        System.out.println("Order details after insertion");
        for (String orderDetail : orderQueue) {
            System.out.println(orderDetail);
            orderQueue.remove("order number 1");
        }
        System.out.println("priority order "+orderQueue.poll());
    }

}
   

Output

Order details after insertion

order number 1

order number 2 premium

order number 3

order number 4

priority order order number 2 premium

Thread safe TreeSet (ConcurrentSkipListSet) Example

Example

package com.vinod.concurrency;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
/**
 * Thread safe implementation for TreeSet.
 * @author vinod.kumaran
 *
 */
public class ConcurrentSkipListSetExample {
	public static void main(String args[]) {
		Set<String> treeSet = new ConcurrentSkipListSet<String>();
		treeSet.add("sunday");
		treeSet.add("monday");
		treeSet.add("tuesday");
		Iterator<String> treeSetIterator = treeSet.iterator();
		while (treeSetIterator.hasNext()) {
			String value = treeSetIterator.next();
			treeSet.add("wednesday");
		}
		System.out.println(treeSet);
	}
}

Output



[monday, sunday, tuesday, wednesday]


Thread Safe TreeMap (ConcurrentSkipListMap) Example

TreeMap is not thread safe and in case two threads are trying to modify the same object it will throw java.util.ConcurrentModificationException.
java.util.concurrent.ConcurrentSkipListMap is the implementation for Thread safe TreeMap and it will keep the natural ordering.

Example

package com.vinod.concurrency;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
public class ConcurrentSkipListMapExample {
	public static void main(String[] args) {
		// Map<String, String> treeMap = new TreeMap<String, String>();
		Map<String, String> treeMap = new ConcurrentSkipListMap<String, String>();
		treeMap.put("1", "sunday");
		treeMap.put("2", "monday");
		treeMap.put("3", "tuesday");
		for (Map.Entry entry : treeMap.entrySet()) {
			System.out.println(entry.getKey());
			treeMap.remove("3");
		}
		System.out.println(treeMap);
	}
}

Output



1
2
{1=sunday, 2=monday}


Thread Safe LinkedList (ConcurrentLinkedDeque) Example

java.util.concurrent.ConcurrentLinkedDeque is the thread safe implementation for LinkedList. This is same as LinkedList except the thread safe feature. Here is one example to add and remove items in ConcurrentLinkedDeque. If we are using this example with LinkedList it will throw ConcurrentModification Exception.

Example

package com.vinod.concurrency;
import java.util.concurrent.ConcurrentLinkedDeque;
/**
 * Thread safe implementation of linked list.
 * 
 * @author vinod.kumaran
 *
 */
public class ConcurrentLinkedDequeExample {
	public static void main(String[] args) {
		ConcurrentLinkedDeque<String> linkedList = new ConcurrentLinkedDeque<String>();
		// List<String> linkedList = new LinkedList<String>();
		linkedList.add("sunday");
		linkedList.add("monday");
		linkedList.add("tuesday");
		for (String s : linkedList) {
			System.out.print(s + "->");
			linkedList.remove("sunday");
		}
		System.out.println(linkedList);
	}
}

Output



sunday->monday->tuesday->[monday, tuesday]



CopyOnWriteArraySet (Thread safe HashSet) Example

CopyOnWriteArraySet is a thread safe Set implementation and it is suitable for applications in which set sizes generally stay small read only operations and needs to prevent interference among threads during traversal.

Example

package com.vinod.concurrency;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
public class CopyOnArraySetExample {
	// ThreadSafe Set implemenation as part of java concurrency api
	public static void main(String[] args) {
		HashSet<String> al = new HashSet<String>();
		al.add("sunday");
		al.add("monday");
		al.add("tuesday");
		Iterator<String> alIterator = al.iterator();
		while (alIterator.hasNext()) {
			String value = alIterator.next();
			al.add("wednesday");
		}
		System.out.println(al);
		CopyOnWriteArraySet<String> coal = new CopyOnWriteArraySet<String>();
		coal.add("sunday");
		coal.add("monday");
		coal.add("tuesday");
		Iterator<String> coalIterator = coal.iterator();
		while (coalIterator.hasNext()) {
			String value = coalIterator.next();
			coal.add("wednesday");
		}
		System.out.println(coal);
	}
}

Output


Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:806)
    at java.util.HashMap$KeyIterator.next(HashMap.java:841)
    at com.vinod.concurrency.CopyOnArraySetExample.main(CopyOnArraySetExample.java:17)


This exception is from HashSet iteration, during iteration we are trying to add values and it is throwing ConcurrentModificationException.
Comment below line and run it again.


//al.add("wednesday");


Output


[monday, sunday, tuesday]
[sunday, monday, tuesday, wednesday]

Java Priority Queue Example

Priority Queue introduced as part of Java 1.5 and it is an unbounded queue based on a priority heap.

Elements in the queues are in natural ordering or by a comparator provided by at queue construction time.

It does not allow null values.

Example:


Here is one simple example to create a PriorityQueue to store order details and our priority is to process premium orders first.

package com.vinod;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class PriorityQueueTest {

public static void main(String[] args) {

// Creating Priority Queue and inserting objects
Comparator<String> pqc = new PQueueComparator();
Queue<String> orderQueue = new PriorityQueue<String>(100, pqc);
orderQueue.add("order number 1");
orderQueue.add("order number 2 premium");
orderQueue.add("order number 3");
orderQueue.add("order number 4");
System.out.println("Order details after insertion");
for (String orderDetail : orderQueue) {
System.out.println(orderDetail);
}
System.out.println("priority order " + orderQueue.poll());
}

}

class PQueueComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
if (s1.length() < s2.length()) {
return 1;
}
if (s1.length() > s2.length()) {
return -1;
}

return 0;
}

}

Ouput:

Order details after insertion
order number 2 premium
order number 1
order number 3
order number 4
priority order order number 2 premium

Different ways to Iterate ArrayList- Example

package com.pretech;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListLoop {
	public static void main(String[] args) {
		List<String> weekdays = new ArrayList<String>();
		weekdays.add("Monday");
		weekdays.add("Tuesday");
		weekdays.add("Wednesday");
		System.out.println("ITERATE USING FOR LOOP");
		for (int num = 0; num < weekdays.size(); num++) {
			System.out.println(weekdays.get(num));
		}
		System.out.println("ITERATE USING ADVANCED FOR LOOP");
		for (String str : weekdays) {
			System.out.println(str);
		}
		
		System.out.println("ITERATE USING util.Iterator");
		Iterator<String> i = weekdays.iterator();
		while (i.hasNext()) {
			System.out.println(i.next());
		}
		
		
		System.out.println("ITERATE USING WHILE LOOP");
		int num = 0;
		while (weekdays.size() > num) {
			System.out.println(weekdays.get(num));
			num++;
		}
	}
}

Output



ITERATE USING FOR LOOP
Monday
Tuesday
Wednesday
ITERATE USING ADVANCED FOR LOOP
Monday
Tuesday
Wednesday
ITERATE USING util.Iterator
Monday
Tuesday
Wednesday
ITERATE USING WHILE LOOP
Monday
Tuesday
Wednesday


Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts