Java Collections Cheat Sheet

The Java Collections Framework (JCF) provides a comprehensive architecture of interfaces, classes, and algorithms to store and manipulate groups of data efficiently. Whether you are preparing for technical interviews or building enterprise microservices, knowing when to use ArrayList, HashMap, HashSet, or TreeMap is essential for writing high-performance Java applications.

This comprehensive, developer-focused Java Collections Cheat Sheet covers core interface hierarchies, popular implementations, time complexities, and utility methods.

1. Core Interfaces and Implementations

The collection hierarchy revolves around three core interfaces: List, Set, and Map (note that Map is separate from the Collection root interface).

C
import java.util.*;

public class CollectionsCheatSheet {
    public static void main(String[] args) {
        // List: Ordered collection, allows duplicate elements
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Spring");
        arrayList.add("Hibernate");

        // Set: Unique elements, no duplicates allowed
        Set<String> hashSet = new HashSet<>();
        hashSet.add("Java");
        hashSet.add("Java"); // Ignored (Duplicate)

        // Map: Key-Value pairs with unique keys
        Map<Integer, String> hashMap = new HashMap<>();
        hashMap.put(1, "Admin");
        hashMap.put(2, "Developer");
        
        System.out.println("List size: " + arrayList.size() + " | Set size: " + hashSet.size());
    }
}

2. Time Complexities of Popular Collections

Choosing the correct data structure depends heavily on the time complexity of core operations (add, get, remove, search).

  • ArrayList: O(1) random access by index, O(N) search and insertion in middle, O(1) amortized insertion at end.
  • LinkedList: O(N) random access, O(1) insertion/deletion at known iterator position.
  • HashSet / HashMap: O(1) average time complexity for add, remove, and contains operations.
  • TreeSet / TreeMap: O(log N) time complexity for operations while keeping keys strictly sorted.

3. Iteration and Stream Processing

Modern Java provides robust functional idioms via streams and lambdas to process collection elements concisely.

C
import java.util.List;
import java.util.Arrays;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

        // Filter even numbers and compute their sum using Stream API
        int sumOfEvens = numbers.stream()
            .filter(n -> n % 2 == 0)
            .mapToInt(Integer::intValue)
            .sum();

        System.out.println("Sum of evens: " + sumOfEvens); // 12
    }
}

Conclusion

Keep this Java Collections reference cheat sheet handy to select the most optimal collection interface and implementation for your backend services and application logic.