Archives: Collections

Java – Deque Example

Java Deque Example with Adding, Iterating and Removing of Collection Elements

public interface Deque<E> extends Queue<E>

A linear collection that supports element insertion and removal at both ends. This interface defines methods to access the elements at both ends of the deque. Methods are provided to insert, remove, and examine the element.

Output:

[Element 6 (Head), Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail), Element 5 (Tail), Element 7 (Tail)]

Standard Iterator
Element 6 (Head)
Element 4 (Head)
Element 2 (Head)
Element 1 (Tail)
Element 3 (Tail)
Element 5 (Tail)
Element 7 (Tail)
Reverse Iterator
Element 7 (Tail)
Element 5 (Tail)
Element 3 (Tail)
Element 1 (Tail)
Element 2 (Head)
Element 4 (Head)
Element 6 (Head)
Peek Element 6 (Head)
After peek: [Element 6 (Head), Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail), Element 5 (Tail), Element 7 (Tail)]
Pop Element 6 (Head)
After pop: [Element 4 (Head), Element 2 (Head), Element 1 (Tail), Element 3 (Tail), Element 5 (Tail), Element 7 (Tail)]
Contains element 3: true



Java – Synchronized HashMap Example

Synchronized HashMap Example in Java

HashMap is a non-synchronized collection class. If we need to perform thread-safe operations on it then we must need to synchronize it explicitly.
Iterator should be used in a synchronized block even if we have synchronized the HashMap explicitly.



Java – Map Iterate Example

Iterating Map / HashMap in different ways – Java Example