Skip to main content

Command Palette

Search for a command to run...

Mastering the Java Collection Framework — From Lists to Maps

Published
10 min readView as Markdown
Mastering the Java Collection Framework — From Lists to Maps

Java Collection Framework – Quick Reference and Practical Guide

When we start coding in Java, we often remember the logic but get stuck on the syntax of how to use certain classes in the Collection Framework. This section summarizes the most commonly used ones — HashMap and HashSet — with practical examples, traversal methods, and a list of key methods you’ll actually use.

1. HashMap in Java

A HashMap is part of the Java Collections Framework and is used to store data in key-value pairs.
It allows one null key and multiple null values, and it does not maintain insertion order.

Example: Creating and Traversing a HashMap

import java.util.HashMap;
import java.util.Map;

public class HashMapTraversal {
    public static void main(String[] args) {
        HashMap<String, Integer> studentScores = new HashMap<>();

        studentScores.put("Alice", 85);
        studentScores.put("Bob", 92);
        studentScores.put("Charlie", 78);

        for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
            String studentName = entry.getKey();
            Integer score = entry.getValue();
            System.out.println(studentName + ": " + score);
        }
    }
}

Commonly Used HashMap Methods

MethodDescriptionReturn Type
clear()Removes all entries from the map.void
clone()Creates a shallow copy of the HashMap.Object
compute()Updates a value for a key based on its current value (if present).V
computeIfAbsent()Computes a value only if the key is not already associated with a value.V
computeIfPresent()Computes a new value only if the key is already present.V
containsKey(Object key)Checks if a specific key exists in the map.boolean
containsValue(Object value)Checks if a specific value exists in the map.boolean
entrySet()Returns a set of all key-value pairs.Set<Map.Entry<K,V>>
forEach()Performs an action for each entry.void
get(Object key)Returns the value mapped to the specified key.V
getOrDefault(Object key, V defaultValue)Returns the value for a key or a default if not found.V
isEmpty()Checks if the map is empty.boolean
keySet()Returns a set of all keys.Set<K>
merge()Combines values or inserts a value if the key doesn’t exist.V
put(K key, V value)Inserts or updates a key-value pair.V
putAll(Map<? extends K,? extends V> m)Copies all mappings from another map.void
putIfAbsent(K key, V value)Adds the key-value pair only if the key is not already present.V
remove(Object key)Removes a mapping by key.V / boolean
replace(K key, V value)Updates the value for an existing key.V / boolean
replaceAll()Replaces every value with the result of an operation.void
size()Returns the total number of entries.int
values()Returns a collection of all values.Collection<V>

2. HashSet in Java

A HashSet is a collection that contains unique elements only. It is backed by a HashMap, meaning duplicates are automatically ignored.
HashSet does not maintain insertion order, and the iteration order may vary.

Example: Iterating through a HashSet

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetTraversal {
    public static void main(String[] args) {
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Apple");
        hashSet.add("Banana");
        hashSet.add("Cherry");

        Iterator<String> iterator = hashSet.iterator();
        System.out.println("Traversing using Iterator:");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Commonly Used HashSet Methods

MethodDescription
add(E e)Adds an element if not already present; returns false if duplicate.
clear()Removes all elements from the set.
contains(Object o)Checks whether an element exists in the set.
remove(Object o)Removes a specific element if present.
iterator()Returns an iterator for traversing elements.
isEmpty()Checks whether the set is empty.
size()Returns the number of elements in the set.
clone()Creates a shallow copy of the set.

3. ArrayList in Java

An ArrayList is a resizable array implementation of the List interface.
It maintains insertion order, allows duplicate elements, and provides random access to elements in constant time.

Example: Traversing an ArrayList

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

public class ArrayListExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        System.out.println("Using for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Commonly Used ArrayList Methods

MethodDescription
add(E e)Adds an element to the list.
add(int index, E element)Inserts an element at a specific position.
remove(Object o)Removes the first occurrence of the specified element.
remove(int index)Removes the element at the specified position.
get(int index)Returns the element at the given index.
set(int index, E element)Replaces the element at the given index.
size()Returns the number of elements in the list.
isEmpty()Checks if the list is empty.
contains(Object o)Returns true if the list contains the specified element.
clear()Removes all elements from the list.
indexOf(Object o)Returns the index of the first occurrence of the element.
subList(int fromIndex, int toIndex)Returns a portion of the list between given indexes.

4. LinkedList in Java

A LinkedList is a doubly-linked list implementation of the List and Deque interfaces.
It maintains insertion order and allows both sequential access and queue-like operations.

Example: Traversing a LinkedList

import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList<String> cities = new LinkedList<>();
        cities.add("Pune");
        cities.add("Mumbai");
        cities.add("Delhi");

        System.out.println("Traversing LinkedList:");
        for (String city : cities) {
            System.out.println(city);
        }
    }
}

Commonly Used LinkedList Methods

MethodDescription
add(E e)Adds an element at the end of the list.
addFirst(E e)Adds an element at the beginning.
addLast(E e)Adds an element at the end.
removeFirst()Removes the first element.
removeLast()Removes the last element.
getFirst()Returns the first element.
getLast()Returns the last element.
peek()Retrieves the head element without removing it.
poll()Retrieves and removes the head element.
offer(E e)Adds an element at the end (like a queue).
clear()Removes all elements from the list.

5. TreeSet in Java

A TreeSet is a sorted set that stores elements in ascending order using a balanced tree (Red-Black Tree).
It does not allow duplicate elements.

Example: Traversing a TreeSet

import java.util.TreeSet;

public class TreeSetExample {
    public static void main(String[] args) {
        TreeSet<Integer> numbers = new TreeSet<>();
        numbers.add(30);
        numbers.add(10);
        numbers.add(20);

        System.out.println("Elements in ascending order:");
        for (Integer num : numbers) {
            System.out.println(num);
        }
    }
}

Commonly Used TreeSet Methods

MethodDescription
add(E e)Adds an element in sorted order.
remove(Object o)Removes the specified element.
first()Returns the first (lowest) element.
last()Returns the last (highest) element.
higher(E e)Returns the next higher element.
lower(E e)Returns the next lower element.
headSet(E toElement)Returns elements less than toElement.
tailSet(E fromElement)Returns elements greater than or equal to fromElement.
subSet(E fromElement, E toElement)Returns a portion of the set.
clear()Removes all elements.
size()Returns the total number of elements.

6. TreeMap in Java

A TreeMap stores key-value pairs in sorted order of keys.
It’s implemented using a Red-Black Tree, and it does not allow null keys.

Example: Traversing a TreeMap

import java.util.TreeMap;
import java.util.Map;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>();
        map.put(3, "Banana");
        map.put(1, "Apple");
        map.put(2, "Cherry");

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
    }
}

Commonly Used TreeMap Methods

MethodDescription
put(K key, V value)Adds a key-value pair.
remove(Object key)Removes a mapping for the specified key.
firstKey()Returns the lowest key.
lastKey()Returns the highest key.
higherKey(K key)Returns the next higher key.
lowerKey(K key)Returns the next lower key.
ceilingEntry(K key)Returns entry ≥ given key.
floorEntry(K key)Returns entry ≤ given key.
descendingMap()Returns a reverse-order view of the map.
headMap(K toKey)Returns keys less than toKey.
tailMap(K fromKey)Returns keys greater than or equal to fromKey.

7. PriorityQueue in Java

A PriorityQueue is a queue where elements are ordered according to their natural order or a custom comparator.
By default, it functions as a min-heap.

Example: Using a PriorityQueue

import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(40);
        pq.add(10);
        pq.add(30);

        while (!pq.isEmpty()) {
            System.out.println(pq.poll());
        }
    }
}

Commonly Used PriorityQueue Methods

MethodDescription
add(E e)Inserts an element into the queue.
offer(E e)Inserts an element; returns false if full.
peek()Returns the head element without removing it.
poll()Retrieves and removes the head element.
remove(Object o)Removes a specific element.
clear()Removes all elements.
isEmpty()Checks if the queue is empty.
size()Returns the number of elements.

8. Stack in Java

A Stack follows Last In, First Out (LIFO) order.
It extends Vector, though Deque is preferred in modern Java for stack operations.

Example: Using Stack

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        stack.push("HTML");
        stack.push("CSS");
        stack.push("JavaScript");

        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }
}

Commonly Used Stack Methods

MethodDescription
push(E item)Pushes an item onto the stack.
pop()Removes and returns the top item.
peek()Returns the top item without removing it.
isEmpty()Checks if the stack is empty.
search(Object o)Returns position of an item from the top.

9. Queue in Java

A Queue follows First In, First Out (FIFO) order.
It’s used for task scheduling or managing requests.

Example: Using Queue

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        queue.add(10);
        queue.add(20);
        queue.add(30);

        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}

Commonly Used Queue Methods

MethodDescription
add(E e)Inserts an element; throws exception if full.
offer(E e)Inserts element; returns false if full.
peek()Returns head without removing.
poll()Retrieves and removes head.
remove()Removes head; throws exception if empty.
isEmpty()Checks if queue is empty.

10. Deque in Java

A Deque (Double-Ended Queue) allows insertion and removal of elements from both ends.
It can function as both a stack and a queue.

Example: Using Deque

import java.util.ArrayDeque;
import java.util.Deque;

public class DequeExample {
    public static void main(String[] args) {
        Deque<String> deque = new ArrayDeque<>();
        deque.addFirst("Front");
        deque.addLast("Back");

        System.out.println("Front: " + deque.removeFirst());
        System.out.println("Back: " + deque.removeLast());
    }
}

Commonly Used Deque Methods

MethodDescription
addFirst(E e)Inserts element at the front.
addLast(E e)Inserts element at the end.
removeFirst()Removes element from the front.
removeLast()Removes element from the end.
peekFirst()Returns first element without removing.
peekLast()Returns last element without removing.
pollFirst()Retrieves and removes first element.
pollLast()Retrieves and removes last element.
clear()Removes all elements.
isEmpty()Checks if deque is empty.

Closing Thoughts

The Java Collection Framework provides powerful data structures that handle almost all common storage and manipulation needs.
Understanding their basic syntax and knowing when to use which — List for ordered data, Set for unique data, Map for key-value pairs, and Queue for sequential processing — can make your code cleaner and more efficient.