Collections Framework

The Java Collections Framework is a set of classes and interfaces in Java that makes it easy to store, manage, and process groups of data. Collections are like containers that hold multiple items, similar to a shopping bag that can hold groceries. The framework provides different types of collections to store and organize data efficiently.

Why Use Collections?

Collections provide a flexible and efficient way to:

  • Store data dynamically without needing to know the size beforehand.
  • Organize and manipulate data using various data structures like lists, sets, and maps.
  • Perform operations like searching, sorting, and iterating over data easily.

Key Interfaces in the Collections Framework

The Java Collections Framework has a few important interfaces that define different types of collections:

  • List: Stores an ordered collection of elements. Allows duplicates.
    • Examples: ArrayList, LinkedList
  • Set: Stores a unique collection of elements. No duplicates are allowed.
    • Examples: HashSet, LinkedHashSet, TreeSet
  • Map: Stores key-value pairs. Keys are unique, and each key maps to one value.
    • Examples: HashMap, TreeMap, LinkedHashMap
  • Queue: Stores elements in a way that supports processing in a specific order (usually FIFO - First In, First Out).
    • Examples: PriorityQueue, LinkedList (as a queue)

Common Collection Classes

Here are some commonly used classes in the Collections Framework:

  • ArrayList: A resizable array that allows random access to elements. Good for reading data but slower for insertions and deletions.
  • LinkedList: A list where elements are linked to each other. Good for frequent insertions and deletions.
  • HashSet: A set that stores unique elements in an unordered way. Fast for lookups.
  • TreeSet: A set that stores unique elements in a sorted order.
  • HashMap: A map that stores key-value pairs. It’s fast for retrieving data by key.
  • TreeMap: A map that keeps keys sorted in a natural order.

Basic Operations on Collections

Collections in Java support common operations like adding, removing, and checking elements. Here’s a quick overview of these operations:

  • Adding elements: add() for lists and sets, put() for maps.
  • Removing elements: remove() for lists and sets, remove(key) for maps.
  • Checking for elements: contains() for lists and sets, containsKey() and containsValue() for maps.
  • Iterating over elements: Using loops like for-each or iterators to go through each item in a collection.

Benefits of Using the Collections Framework

  • Efficiency: Collections provide efficient data structures for storing and processing data.
  • Flexibility: Collections are dynamic, so they can grow or shrink in size as needed.
  • Code Readability: Predefined classes and methods make the code easier to read and maintain.

Collection Types

List Interface

  • Allows Duplicates: Elements can repeat. Ordered: Elements are kept in the order they were added.
  • Popular Classes:
    • ArrayList: A resizable array; great for fast access.
    • LinkedList: Doubly-linked list; good for frequent insertions and deletions.

Example of ArrayList

Java
Copy
import java.util.ArrayList;

public class ListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Alice"); // Duplicate allowed
        System.out.println(names); // [Alice, Bob, Alice]
    }
}

Set Interface

  • No Duplicates: Each element is unique.
  • Unordered: Does not maintain insertion order (except for LinkedHashSet).
  • Popular Classes:
    • HashSet: Stores elements in no particular order.
    • TreeSet: Stores elements in sorted order.

Example of HashSet:

Java
Copy
import java.util.HashSet;

public class SetExample {
    public static void main(String[] args) {
        HashSet<String> cities = new HashSet<>();
        cities.add("New York");
        cities.add("Paris");
        cities.add("New York"); // Duplicate, won't be added
        System.out.println(cities); // [Paris, New York]
    }
}

Map Interface

  • Key-Value Pairs: Each element is stored as a key-value pair.
  • Unique Keys: Each key is unique, but values can be duplicated.
  • Popular Classes:
    • HashMap: Stores keys and values in an unordered way.
    • TreeMap: Stores keys in sorted order.

Example of HashMap:

Java
Copy
import java.util.HashMap;

public class MapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> ages = new HashMap<>();
        ages.put("Alice", 25);
        ages.put("Bob", 30);
        System.out.println(ages); // {Alice=25, Bob=30}
    }
}

Queue Interface

  • FIFO (First-In-First-Out): Elements are processed in the order they are added.
  • Popular Classes:
    • LinkedList: Implements both List and Queue.
    • PriorityQueue: Orders elements according to their natural ordering or a comparator.

Example of PriorityQueue:

Java
Copy
import java.util.PriorityQueue;

public class QueueExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> numbers = new PriorityQueue<>();
        numbers.add(5);
        numbers.add(1);
        numbers.add(3);
        System.out.println(numbers.poll()); // 1 (smallest element)
    }
}

Utilities in the Collections Class

Java provides the Collections utility class with helpful methods to perform actions on collections. Here are some common methods:

  • Sorting: Collections.sort(list).
  • Finding Max/Min: Collections.max(collection) and Collections.min(collection).
  • Reversing: Collections.reverse(list).
  • Shuffle: Collections.shuffle(list) to randomly reorder elements.
Java
Copy
import java.util.ArrayList;
import java.util.Collections;

public class CollectionsExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(3);
        numbers.add(1);
        numbers.add(5);
        
        Collections.sort(numbers);
        System.out.println(numbers); // [1, 3, 5]
    }
}

When to Use Which Collection?

Choosing the right collection depends on your requirements:

  • Use List when you need ordered elements and duplicates are allowed.
  • Use Set when you need unique elements, and order isn’t important.
  • Use Map when you need to associate keys with values (like a dictionary).
  • Use Queue when you need to process elements in the order they’re added.