Lesson 49 of 50 – Java Collections Framework
98%

Java Collections Framework

The Java Collections Framework provides classes and interfaces for storing, organizing, and processing groups of objects. It includes collections such as lists, sets, and queues, as well as the Map interface for storing key-value pairs.

1. Introduction to Collections

Suppose you want to store the names of 100 students. Creating 100 separate variables would be difficult. Collections allow you to store and manage multiple values using a single object.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();

        names.add("Rahul");
        names.add("Amit");
        names.add("Priya");

        System.out.println(names);
    }
}

Output:

[Rahul, Amit, Priya]

Collections can grow or shrink dynamically, depending on the implementation.

2. Collections Framework Hierarchy

The main parts of the Collections Framework include:

  • List: An ordered collection that allows duplicates.
  • Set: A collection that does not allow duplicate elements.
  • Queue: A collection designed for holding elements before processing.
  • Deque: A double-ended queue that supports operations at both ends.
  • Map: Stores key-value pairs. It is part of the framework but does not extend the Collection interface.

Common implementations:

Interface Implementation Purpose
List ArrayList Resizable array
List LinkedList Linked-node list
Set HashSet Unique elements
Set TreeSet Sorted unique elements
Queue / Deque ArrayDeque Queue and stack-style operations
Map HashMap Key-value pairs

3. ArrayList in Java

ArrayList stores elements in an ordered, resizable list. It allows duplicate values and provides fast access by index.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");

        System.out.println(fruits);
        System.out.println(fruits.get(1));
    }
}

Output:

[Apple, Mango, Banana]
Mango

Common ArrayList methods:

  • add() adds an element.
  • get() retrieves an element by index.
  • set() replaces an element.
  • remove() removes an element.
  • size() returns the number of elements.
  • contains() checks whether an element exists.

4. LinkedList in Java

LinkedList implements both the List and Deque interfaces. It stores elements in linked nodes and supports operations at the beginning and end of the list.

import java.util.LinkedList;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> cities = new LinkedList<>();

        cities.add("Delhi");
        cities.add("Patna");
        cities.addFirst("Gaya");
        cities.addLast("Mumbai");

        System.out.println(cities);
    }
}

Output:

[Gaya, Delhi, Patna, Mumbai]

LinkedList can be useful for operations at the ends of a list. It generally has slower indexed access than ArrayList.

5. HashSet in Java

A HashSet stores unique elements. Adding the same element more than once does not create a duplicate. Its iteration order is not guaranteed.

import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet<String> colors = new HashSet<>();

        colors.add("Red");
        colors.add("Blue");
        colors.add("Green");
        colors.add("Red");

        System.out.println(colors);
        System.out.println(colors.contains("Blue"));
    }
}

Example output:

[Red, Blue, Green]
true

The order shown in the set output is only illustrative; HashSet does not guarantee a particular iteration order.

6. TreeSet in Java

A TreeSet stores unique elements in sorted order according to their natural ordering or a supplied comparator.

import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        TreeSet<Integer> numbers = new TreeSet<>();

        numbers.add(50);
        numbers.add(10);
        numbers.add(30);
        numbers.add(10);

        System.out.println(numbers);
    }
}

Output:

[10, 30, 50]

TreeSet is useful when you need unique elements in sorted order. Its elements must be comparable, or a suitable comparator must be provided.

7. HashMap in Java

A HashMap stores data as key-value pairs. Each key is unique, but multiple keys can have the same value.

import java.util.HashMap;

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

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Priya");

        System.out.println(students.get(102));
        System.out.println(students.containsKey(101));
    }
}

Output:

Amit
true

Important HashMap methods:

  • put(key, value) adds or updates an entry.
  • get(key) retrieves the value for a key.
  • remove(key) removes an entry.
  • containsKey(key) checks whether a key exists.
  • keySet() returns the set of keys.
  • values() returns the collection of values.

8. Iterating Through a Collection

A for-each loop is a simple way to process every element in a collection.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> languages = new ArrayList<>();

        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");

        for (String language : languages) {
            System.out.println(language);
        }
    }
}

Output:

Java
Python
JavaScript

You can also use an iterator when you need explicit traversal or safe removal through the iterator.

import java.util.ArrayList;
import java.util.Iterator;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers =
            new ArrayList<>();

        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        Iterator<Integer> iterator = numbers.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

9. Sorting a Collection

The Collections.sort() method sorts a list into natural order.

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();

        numbers.add(40);
        numbers.add(10);
        numbers.add(30);
        numbers.add(20);

        Collections.sort(numbers);

        System.out.println(numbers);
    }
}

Output:

[10, 20, 30, 40]

To sort the list in descending order:

Collections.sort(numbers, Collections.reverseOrder());

The reverse-order comparator sorts the elements from largest to smallest.

10. Queue and ArrayDeque

A queue commonly processes elements in first-in, first-out (FIFO) order. ArrayDeque can implement a queue and also supports stack-style operations.

import java.util.ArrayDeque;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayDeque<>();

        queue.offer("Rahul");
        queue.offer("Amit");
        queue.offer("Priya");

        System.out.println(queue.poll());
        System.out.println(queue);
    }
}

Output:

Rahul
[Amit, Priya]

offer() adds an element, while poll() retrieves and removes the head of the queue. If the queue is empty, poll returns null.

11. Collections Utility Methods

The Collections utility class provides useful operations for working with collections.

Method Purpose
Collections.sort(list) Sorts a list.
Collections.reverse(list) Reverses the list's current order.
Collections.shuffle(list) Randomly rearranges list elements.
Collections.max(list) Returns the maximum element.
Collections.min(list) Returns the minimum element.
Collections.frequency(list, item) Counts occurrences of an element.
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers =
            new ArrayList<>();

        numbers.add(10);
        numbers.add(20);
        numbers.add(10);
        numbers.add(30);

        System.out.println(Collections.max(numbers));
        System.out.println(Collections.min(numbers));
        System.out.println(Collections.frequency(numbers, 10));
    }
}

Output:

30
10
2

12. Choosing the Right Collection

Requirement Recommended choice
Ordered list with duplicates ArrayList
Frequent operations at both ends ArrayDeque or LinkedList
Unique elements without guaranteed order HashSet
Unique elements in sorted order TreeSet
Key-value lookup HashMap
FIFO queue ArrayDeque or another Queue implementation
Tip: Choose a collection based on the operations your program performs most often, such as searching, sorting, insertion, or removal.

13. Practice Assignments

  1. Create an ArrayList containing five student names and display them.
  2. Add a new element to an ArrayList and remove one element.
  3. Create a LinkedList of city names and add an element at the beginning.
  4. Use a HashSet to remove duplicate numbers.
  5. Create a TreeSet and display numbers in sorted order.
  6. Create a HashMap to store student IDs and names.
  7. Sort a list of integers in ascending and descending order.
  8. Use a Queue to process three student names in FIFO order.
  9. Find the minimum and maximum values in an ArrayList.
  10. Count how many times a number appears in a list.

🧠 Quick Quiz

1. Which collection allows duplicate elements and supports index-based access?




2. Which collection stores unique elements in sorted order?




3. Which collection stores key-value pairs?