BhauAutomation

Collection in Java

The Collection Framework in Java provides classes and interfaces to store, manage, and manipulate groups of objects efficiently. It is one of the most important concepts for Java developers to master.

📘 Topic: Core Java / Collections
Read time: 6 min
📊 Level: Intermediate
🎯 Focus: Data Structures
📖 Overview

What is Collection in Java?

A Collection in Java is a framework that provides an architecture to store and manage a group of objects. It includes interfaces (List, Set, Queue, Map) and classes (ArrayList, HashSet, LinkedList, etc.) for efficient data handling and manipulation.

The Java Collections Framework (JCF) provides reusable, high-performance data structures and algorithms that reduce programming effort and increase performance.

📊 Quick Reference

Collection Types Summary

。FIFO (First-In-First-Out) structure for processing elements
Interface Description Implementing Classes
List Ordered collection, allows duplicates, index-based access ArrayList, LinkedList, Vector, Stack
Set Unordered collection, no duplicates, unique elements HashSet, LinkedHashSet, TreeSet
Queue PriorityQueue, ArrayDeque, LinkedList
Map Key-value pair storage, no duplicate keys, each key maps to one value HashMap, TreeMap, LinkedHashMap, Hashtable
💻 Code Examples

Collection Implementation Examples

List Collection Example - ArrayList

import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Apple"); // Duplicates allowed

        System.out.println("List elements: " + fruits);
        System.out.println("Element at index 1: " + fruits.get(1));
        System.out.println("Size: " + fruits.size());
    }
}

Set Collection Example - HashSet

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<Integer> numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(10); // Duplicate ignored

        System.out.println("Set elements (unique): " + numbers);
        System.out.println("Contains 20? " + numbers.contains(20));
    }
}

Map Collection Example - HashMap

import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> studentMarks = new HashMap<>();
        studentMarks.put("Alice", 90);
        studentMarks.put("Bob", 85);
        studentMarks.put("Charlie", 95);
        
        System.out.println("Student Marks: " + studentMarks);
        System.out.println("Alice's marks: " + studentMarks.get("Alice"));
        
        // Iterating through Map
        for (Map.Entry<String, Integer> entry : studentMarks.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

Queue Collection Example - PriorityQueue

import java.util.PriorityQueue;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<String> queue = new PriorityQueue<>();
        queue.add("Task 1");
        queue.add("Task 2");
        queue.add("Task 3");
        
        System.out.println("Queue: " + queue);
        System.out.println("Removed: " + queue.poll());
        System.out.println("After removal: " + queue);
    }
}
🎯 Key Points

Objectives of Collection Framework

  • Represent and manipulate dynamic data groups efficiently
  • Reduce programming effort using reusable data structures
  • Provide high-performance, flexible data handling
  • Allow interoperability between different collection types
  • Support standard methods for common operations (add, remove, search, sort)

✅ Advantages

  • Reduces development time with ready-to-use data structures
  • Provides dynamic storage (no fixed size limitations)
  • Improves performance with built-in algorithms
  • Ensures consistency across different data types
  • Includes thread-safe implementations (Vector, Hashtable)

⚠️ Limitations

  • Can increase memory overhead compared to primitive arrays
  • Type safety issues in non-generic collections (pre-Java 5)
  • Performance trade-offs with certain operations (e.g., searching)
  • Synchronization overhead in thread-safe collections
🗂️ Hierarchy

Collection Framework Hierarchy

The Collection Framework follows a well-defined hierarchy of interfaces and classes:

📋 List Interface

Ordered collection, allows duplicates, maintains insertion order. Implementations: ArrayList, LinkedList, Vector

⚙️ Set Interface

Unordered collection, no duplicates, unique elements. Implementations: HashSet, TreeSet, LinkedHashSet

🔄 Queue Interface

FIFO structure, processes elements in order. Implementations: PriorityQueue, ArrayDeque

🗺️ Map Interface

Stores key-value pairs, unique keys. Not part of Collection interface but part of framework.

🏆 Best Practices

Best Practices for Java Collections

Always use generics for type safety (ArrayList<String> over ArrayList)

Choose the right collection class based on your requirements

Prefer interfaces over concrete classes (List list = new ArrayList())

Use streams and lambda expressions for cleaner, modern code

Initialize collections with an initial capacity to reduce resizing

Use Collections utility class for sorting, searching, and synchronization