Java Collections Essentials — Part 1

Udaykishore Resu
4 min readDec 9, 2024

--

The Java Collections Framework is one of the most important concepts in Java programming, and it is valued highly during project development and technical interviews. Its importance comes from the fact that this framework can provide optimized solutions for a wide range of data management requirements.

Java Collections

In 1994, the Standard Template Library (STL) was introduced in C++, while Java fell behind in developing a common framework with hierarchical data structures. It wasn’t until late 1998 with the release of the Java Development Kit (JDK) 2 that the Generic Collection Library (JGL) became the most popular collections framework. However, it wasn’t until the Fall of 2004 with the release of JDK 5 that Java received a significant upgrade to its collections framework, leading to the creation of the Java Collections Framework (JCF) that we are familiar with today.

The Java Collections Framework (JCF) don’t just rely on one Collection interface. Instead, it’s the combination of different interfaces, abstract classes, and concrete implementations that form the framework. The primary collection data structures: Lists, sets, and queues.

In simpler terms, a list is a list of items in a specific order, a set is a group of items without duplicates, and a queue is a lineup for processing items in a specific order like first in first out (FIFO) or last in first out (LIFO). These concepts are like mathematical sets but have practical applications in organizing and managing data efficiently.

Collection in Java is a pre-defined class or container which holds the group of objects as a single unit or single entity. Hence, it is also called a container object or collection object in java.

Java Collections Hierarchy

A Brief Introduction to Java Collections Framework Hierarchy:

Iterable (Iterator)

The interface is the root in the collection hierarchy, allowing objects to be the target of the “for-each loop” statement.

An Iterator in Java is an interface designed for traversing and potentially modifying elements in a collection. It provides a uniform way to access elements sequentially, regardless of the underlying collection type. The Iterator interface defines three key methods:

hasNext()

public boolean hasNext()
  • Returns true if there are more elements to iterate over
  • Used to check if the iteration has more elements before calling next()

next()

public E next()
  • Returns the next element in the iteration
  • Advances the iterator to the subsequent element
  • Throws NoSuchElementException if there are no more elements

remove()

public void remove()
  • Removes the last element returned by the iterator from the underlying collection
  • Can be called only once per call to next()
  • Throws IllegalStateException if called without a preceding next() call
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if (name.equals("Uday")) {
iterator.remove(); // Safely remove Uday from the list
}
}

Java provides several ways to iterate over collections, few of other ways as follows.

Enhanced For-Loop (For-Each Loop)

Introduced in Java 5, the enhanced for-loop provides a concise and readable syntax for iterating over collections and arrays.

for (ElementType element : collection) {
// Process element
}

Java 8 forEach Method

Introduced in Java 8, the forEach method leverages lambda expressions for a more functional programming approach.

collection.forEach(element -> {
// Process element
});

Collection

The primary interface in the collection framework, extending Iterable. It defines the core methods for all collection types.

There are three components that extend the collection interface i.e List, Queue and Sets. Let’s discuss about them;

List

An ordered collection that allows duplicate elements.

ArrayList: A resizable array implementation, offering fast random access.

Vector: A thread-safe dynamic array (legacy class).

Stack: A Last-In-First-Out (LIFO) stack, extending Vector.

LinkedList: A doubly-linked list implementation, also implements Deque.

Use cases: When order matters, frequent access by index

Limitations:

  • ArrayList: Slow insertions/deletions in the middle
  • LinkedList: Higher memory overhead

Real-world applications: To-do lists, browser history

Thread-safe: Vector, Stack

Set

A collection that does not allow duplicate elements.

HashSet: Stores elements in a hash table, offering constant-time performance for basic operations.

LinkedHashSet: Hash table and linked list implementation, maintaining insertion order.

SortedSet: A Set that maintains its elements in ascending order.

  • TreeSet: A NavigableSet implementation based on a TreeMap.

Use cases: When uniqueness matters, fast lookups

Limitations:

  • No indexing, no guaranteed order (except TreeSet)

Real-world applications: Unique user IDs, removing duplicates

Thread-safe: CopyOnWriteArraySet

Queue

A collection designed for holding elements prior to processing.

PriorityQueue: An unbounded priority heap, ordering elements either naturally or by a Comparator.

Deque: A double-ended queue that supports element insertion and removal at both ends.

  • ArrayDeque: Resizable-array implementation of Deque.

Use cases: Task scheduling, breadth-first search

Limitations:

  • Limited access to elements (mainly head)

Real-world applications: Print job queues, CPU scheduling

Thread-safe: BlockingQueue implementations (e.g., LinkedBlockingQueue)

Map

An object that maps keys to values, cannot contain duplicate keys.

AbstractMap: Skeletal implementation of the Map interface.

HashMap: Hash table based implementation of Map.

EnumMap: Specialized Map implementation for use with enum type keys.

SortedMap: A Map that maintains its entries in ascending key order.

  • NavigableMap: A SortedMap extended with navigation methods.
  • TreeMap: A Red-Black tree based NavigableMap implementation.

Use cases: Key-value associations, fast lookups

Limitations:

  • No direct iteration (use keySet(), values(), or entrySet())

Real-world applications: Caches, dictionaries, configuration settings

Thread-safe: ConcurrentHashMap, Hashtable (legacy)

A detailed breakdown of List collection type will be covered in Java Collections Essentials — Part 2

--

--

Udaykishore Resu
Udaykishore Resu

Written by Udaykishore Resu

Senior Software Engineer with 11+ years in cloud tech, API design, and microservices. Expertise in Golang, Java, Scala. AWS certified. Based in Atlanta, USA.

No responses yet