Java Tutorial 0/145 lessons ~6 min read Lesson 24

    Collections Framework

    java collections framework JCF ArrayList HashMap HashSet List Set Map Queue generics Collections sort

    Course progress0%
    Focus
    23 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    In the previous lessons, you learned about Arrays, Strings, Object-Oriented Programming, and Exception Handling.

    Arrays are useful when the number of elements is fixed.

    Example:

    code
    int[] numbers = new int[100];

    But what if your application needs to:

    • Add new users dynamically
    • Remove products from a shopping cart
    • Store millions of transactions
    • Search customers efficiently
    • Sort employee records
    • Store unique values
    • Map usernames to passwords

    Arrays become limited because:

    • Fixed size
    • Difficult insertion/deletion
    • Limited utility methods
    • No built-in sorting/searching capabilities

    Java solves these problems through the Java Collections Framework (JCF).

    The Java Collections Framework is one of the most important topics for enterprise Java development and is extensively used in:

    • Spring Boot
    • Hibernate
    • Microservices
    • REST APIs
    • Kafka Applications
    • Banking Systems
    • E-Commerce Platforms
    • Android Development
    • Big Data Applications

    Every Java developer is expected to have a strong understanding of the Collections Framework.

    In this lesson, you'll learn:

    • What is Java Collections Framework?
    • Why Collections are Needed
    • Collections Architecture
    • Collection vs Collections
    • Iterable Interface
    • Collection Interface
    • List
    • Set
    • Queue
    • Map
    • Generics
    • Performance Characteristics
    • Choosing the Right Collection
    • Best Practices
    • Common Mistakes
    • Hands-on Exercises
    • Professional Interview Questions

    What is Java Collections Framework?

    The Java Collections Framework (JCF) is a unified architecture for storing, manipulating, searching, sorting, and processing groups of objects.

    It provides:

    • Interfaces
    • Implementations
    • Algorithms

    Instead of creating custom data structures every time, developers use the optimized implementations provided by Java.

    Why Collections?

    Imagine an online shopping website.

    Customers keep adding products.

    code
    Laptop
    Mouse
    Keyboard
    Phone
    Tablet

    The number of products is unknown.

    Using arrays:

    code
    Product[] cart = new Product[5];

    Problems:

    • Fixed size
    • Difficult to resize
    • Slow insertion
    • Difficult deletion

    Using Collections:

    code
    List<Product> cart = new ArrayList<>();

    The list grows automatically.

    Benefits of Collections

    Collections provide:

    • Dynamic resizing
    • Fast searching
    • Easy insertion
    • Easy deletion
    • Sorting
    • Filtering
    • Iteration
    • Thread-safe implementations
    • Generic type safety

    Collection Framework Architecture

    code
    Iterable
    Collection
    ┌──────────┼──────────┐
    │ │ │
    List Set Queue
    │ │ │
    ArrayList HashSet PriorityQueue
    LinkedList LinkedHashSet ArrayDeque
    Vector TreeSet
    Stack

    Separate from the Collection hierarchy:

    code
    Map
    HashMap
    LinkedHashMap
    TreeMap
    Hashtable

    Map is part of the Collections Framework but does not extend the Collection interface.

    Iterable Interface

    Iterable is the root interface for all collection types.

    It enables the enhanced for loop.

    Example:

    code
    List<String> names = new ArrayList<>();
    for(String name : names){
    System.out.println(name);
    }

    Internally, the enhanced for loop uses an Iterator.

    Collection Interface

    The Collection interface provides common operations.

    Important methods:

    code
    add()
    remove()
    contains()
    size()
    isEmpty()
    clear()
    iterator()

    All major collection types implement these operations.

    The List Interface

    A List:

    • Maintains insertion order
    • Allows duplicate elements
    • Supports index-based access

    Example:

    code
    List<String> cities = new ArrayList<>();
    cities.add("Delhi");
    cities.add("Hyderabad");
    cities.add("Delhi");

    Output:

    code
    Delhi
    Hyderabad
    Delhi

    Common implementations:

    • ArrayList
    • LinkedList
    • Vector
    • Stack

    The Set Interface

    A Set stores unique elements.

    Duplicates are ignored.

    Example:

    code
    Set<String> colors = new HashSet<>();
    colors.add("Red");
    colors.add("Blue");
    colors.add("Red");

    Output:

    code
    Red
    Blue

    Implementations:

    • HashSet
    • LinkedHashSet
    • TreeSet

    The Queue Interface

    A Queue follows the FIFO principle.

    code
    First In
    First Out

    Example:

    code
    Queue<String> queue = new LinkedList<>();
    queue.offer("A");
    queue.offer("B");
    queue.offer("C");

    Removing:

    code
    queue.poll();

    Output:

    code
    A

    The Map Interface

    A Map stores key-value pairs.

    Example:

    code
    Map<Integer,String> employees = new HashMap<>();
    employees.put(101,"Rahul");
    employees.put(102,"Amit");

    Retrieving:

    code
    System.out.println(employees.get(101));

    Output:

    code
    Rahul

    Maps do not allow duplicate keys.

    Generics in Collections

    Before Java 5:

    code
    ArrayList list = new ArrayList();

    Problem:

    code
    list.add("Java");
    list.add(100);
    list.add(true);

    No type safety.

    Modern Java:

    code
    List<String> languages =
    new ArrayList<>();

    Now only Strings are allowed.

    Benefits:

    • Compile-time type checking
    • No explicit casting
    • Better readability
    • Fewer runtime errors

    Collection Performance Overview

    CollectionSearchInsertDeleteOrderingDuplicates
    ArrayListFast by indexFast (end)ModerateYesYes
    LinkedListSlow by indexFastFastYesYes
    HashSetVery FastVery FastVery FastNoNo
    TreeSetModerateModerateModerateSortedNo
    HashMapVery FastVery FastVery FastNoKeys No
    TreeMapModerateModerateModerateSorted KeysKeys No

    Note: Average-case performance for HashMap and HashSet operations is typically O(1), while TreeMap and TreeSet operations are generally O(log n) because they are based on balanced tree structures.

    Collection vs Collections

    Many developers confuse these.

    CollectionCollections
    InterfaceUtility Class
    Stores objectsProvides helper methods
    Parent of List, Set, QueueContains sort(), reverse(), shuffle(), etc.

    Example:

    code
    Collections.sort(list);

    Choosing the Right Collection

    RequirementRecommended Collection
    Ordered ListArrayList
    Frequent Insert/DeleteLinkedList
    Unique ElementsHashSet
    Sorted Unique ElementsTreeSet
    Key-Value DataHashMap
    Sorted Key-Value DataTreeMap
    FIFO ProcessingQueue

    Choosing the right collection improves both performance and maintainability.

    Real-World Example: Shopping Cart

    code
    List<String> cart =
    new ArrayList<>();
    cart.add("Laptop");
    cart.add("Mouse");
    cart.add("Keyboard");
    System.out.println(cart);

    Real-World Example: Employee Directory

    code
    Map<Integer,String> employees =
    new HashMap<>();
    employees.put(101,"Rahul");
    employees.put(102,"Amit");
    employees.put(103,"Jagannath");

    Best Practices

    Program to Interfaces

    Prefer:

    code
    List<String> list =
    new ArrayList<>();

    Instead of:

    code
    ArrayList<String> list =
    new ArrayList<>();

    Use Generics

    Always specify the generic type.

    Choose the Correct Collection

    Do not use ArrayList when uniqueness is required.

    Avoid Unnecessary Synchronization

    Prefer non-synchronized collections unless thread safety is required.

    Understand Performance Characteristics

    Selecting the appropriate collection can significantly improve application performance.

    Common Mistakes

    Using Arrays Instead of Collections

    Collections provide greater flexibility for dynamic data.

    Forgetting Generics

    Raw collections can lead to ClassCastException.

    Choosing the Wrong Collection

    Example: Using a List when duplicates are not allowed.

    Assuming HashSet Maintains Order

    HashSet does not guarantee insertion order. Use LinkedHashSet if insertion order is important.

    Assuming HashMap is Sorted

    HashMap does not maintain sorted keys. Use TreeMap when sorted ordering is required.

    Hands-on Exercise

    Create a Java program that:

    1. Creates an ArrayList of employee names.
    2. Adds and removes elements.
    3. Creates a HashSet and demonstrates duplicate removal.
    4. Creates a HashMap of employee IDs and names.
    5. Iterates over all collections using both enhanced for loops and Iterator.
    6. Sorts a list using Collections.sort().
    7. Compares the behavior of ArrayList, HashSet, and HashMap.

    Summary

    The Java Collections Framework provides a standardized, efficient, and extensible way to manage groups of objects. It offers powerful data structures such as List, Set, Queue, and Map, along with utility algorithms and generic type safety. Understanding JCF is essential for building scalable, high-performance enterprise Java applications.

    Key Takeaways

    • JCF provides reusable data structures and algorithms.
    • Collections grow dynamically, unlike arrays.
    • List maintains order and allows duplicates.
    • Set stores unique elements.
    • Queue follows FIFO ordering.
    • Map stores key-value pairs and is not part of the Collection hierarchy.
    • Generics provide compile-time type safety.
    • Program to interfaces rather than implementations.
    • Choose collections based on ordering, uniqueness, and performance requirements.

    Professional Interview Questions

    1What is the Java Collections Framework?

    Professional Answer

    The Java Collections Framework is a unified architecture that provides interfaces, implementations, and algorithms for storing and manipulating groups of objects. It simplifies application development by offering optimized data structures such as List, Set, Queue, and Map, along with utility classes for common operations like sorting and searching.

    Follow-up Questions

    • Why are collections preferred over arrays?
    • Which interfaces are part of the Collection hierarchy?

    Interview Tip: Remember that JCF = Interfaces + Implementations + Algorithms.

    2What is the difference between Collection and Collections?

    Professional Answer

    Collection is the root interface for most collection types such as List, Set, and Queue, defining common operations like add(), remove(), and iterator(). Collections is a utility class that provides static helper methods such as sort(), reverse(), shuffle(), and binarySearch() for working with collections.

    Follow-up Questions

    • Is Map a subtype of Collection?
    • Name three useful methods from the Collections class.

    Interview Tip: A simple memory trick: Collection → Interface, Collections → Utility Class.

    3How do you choose the appropriate Collection implementation?

    Professional Answer

    The choice depends on the application's requirements. Use ArrayList for fast indexed access, LinkedList for frequent insertions and deletions, HashSet for unique elements, TreeSet for sorted unique elements, HashMap for fast key-value lookups, TreeMap for sorted keys, and Queue implementations for FIFO processing. Understanding performance characteristics and data ordering requirements is key to selecting the right implementation.

    Follow-up Questions

    • When would you choose LinkedHashSet instead of HashSet?
    • Why is HashMap generally faster than TreeMap?

    Interview Tip: Interviewers often ask "Which collection would you use and why?" Focus on three factors: Ordering, Duplicates, Performance (time complexity).

    Ready to mark this lesson complete?Track your journey across the entire course.