Java Collections

Understanding Java's powerful data structure framework

📦 What are Java Collections?

Java Collections Framework provides pre-built data structures and algorithms to store, organize, and manipulate groups of objects efficiently in your programs.


// Simple Collections example
import java.util.*;

List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
System.out.println(fruits); // [Apple, Banana]
                                    

Output:

[Apple, Banana]

Key Collection Types

📋

List

Ordered collection that allows duplicates

List<Integer> numbers = new ArrayList<>();
🎯

Set

Collection with unique elements only

Set<String> unique = new HashSet<>();
🗂️

Map

Key-value pairs for data mapping

Map<String, Integer> ages = new HashMap<>();
📊

Queue

First-in-first-out data structure

Queue<String> tasks = new LinkedList<>();

🔹 Collections Hierarchy

Understanding the relationship between different collection types:

// Collection Interface (Root)
//     ├── List Interface
//     │   ├── ArrayList (most common)
//     │   ├── LinkedList
//     │   └── Vector
//     ├── Set Interface
//     │   ├── HashSet (most common)
//     │   ├── LinkedHashSet
//     │   └── TreeSet
//     └── Queue Interface
//         ├── LinkedList
//         └── PriorityQueue

// Map is separate (not part of Collection)
// Map Interface
//     ├── HashMap (most common)
//     ├── LinkedHashMap
//     └── TreeMap

🔹 Basic Collections Operations

Common operations you'll use with all collections:

import java.util.*;

public class CollectionsBasics {
    public static void main(String[] args) {
        // Creating a collection
        List<String> colors = new ArrayList<>();
        
        // Adding elements
        colors.add("Red");
        colors.add("Blue");
        colors.add("Green");
        
        // Checking size
        System.out.println("Size: " + colors.size());
        
        // Checking if contains element
        System.out.println("Has Red: " + colors.contains("Red"));
        
        // Iterating through collection
        for (String color : colors) {
            System.out.println(color);
        }
        
        // Removing element
        colors.remove("Blue");
        System.out.println("After removal: " + colors);
    }
}

Output:

Size: 3
Has Red: true
Red
Blue
Green
After removal: [Red, Green]

🔹 When to Use Which Collection

Quick Selection Guide:

  • ArrayList: When you need fast access by index and don't mind slower insertions/deletions
  • LinkedList: When you frequently insert/delete elements in the middle
  • HashSet: When you need unique elements and fast lookups
  • HashMap: When you need key-value pairs with fast access
  • TreeSet/TreeMap: When you need sorted collections

🧠 Test Your Knowledge

Which collection allows duplicate elements?