⬅ Previous Next ➡

Java Collections Framework

Java Collections Framework: List, Set, Map, ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, Iterators, Comparable & Comparator
  • Collections Framework is a set of classes and interfaces to store and manipulate groups of objects.
  • Main interfaces: List, Set, Map (Map is part of collections framework but not a child of Collection).
  • Benefits: dynamic size, ready-made methods, sorting/searching support, better data handling.

1) List Interface (ArrayList, LinkedList)

  • List allows duplicate elements and maintains insertion order.
  • Access elements by index (0-based).
  • ArrayList: fast random access, slower insert/delete in middle.
  • LinkedList: faster insert/delete, slower random access.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class ListDemo {
    public static void main(String[] args) {

        List<String> topics = new ArrayList<>();
        topics.add("Java");
        topics.add("Collections");
        topics.add("Java"); // duplicate allowed

        System.out.println("ArrayList: " + topics);
        System.out.println("First: " + topics.get(0));

        List<Integer> nums = new LinkedList<>();
        nums.add(10);
        nums.add(20);
        nums.add(15);
        nums.add(1, 99); // insert at index

        System.out.println("LinkedList: " + nums);
    }
}

2) Set Interface (HashSet, TreeSet)

  • Set stores unique elements (no duplicates).
  • HashSet: unordered (no fixed order), fastest for add/search.
  • TreeSet: sorted order (ascending by default), slower than HashSet.
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

class SetDemo {
    public static void main(String[] args) {

        Set<String> hs = new HashSet<>();
        hs.add("Sourav");
        hs.add("Amit");
        hs.add("Sourav"); // duplicate ignored
        System.out.println("HashSet: " + hs);

        Set<Integer> ts = new TreeSet<>();
        ts.add(50);
        ts.add(10);
        ts.add(30);
        System.out.println("TreeSet (sorted): " + ts);
    }
}

3) Map Interface (HashMap, TreeMap)

  • Map stores data as key-value pairs.
  • Keys are unique; values can be duplicate.
  • HashMap: fast, no guaranteed order.
  • TreeMap: sorted by key (ascending).
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

class MapDemo {
    public static void main(String[] args) {

        Map<String, Integer> hm = new HashMap<>();
        hm.put("Java", 90);
        hm.put("DBMS", 85);
        hm.put("Web", 88);

        System.out.println("HashMap: " + hm);
        System.out.println("Java marks: " + hm.get("Java"));

        Map<String, Integer> tm = new TreeMap<>();
        tm.put("C", 80);
        tm.put("Java", 90);
        tm.put("Python", 95);

        System.out.println("TreeMap (sorted by key): " + tm);
    }
}

4) Iterators (Iterator & ListIterator)

  • Iterator is used to traverse collections safely.
  • Methods: hasNext(), next(), remove()
  • ListIterator (List only): can move forward/backward.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class IteratorDemo {
    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("C");

        Iterator<String> it = list.iterator();
        while (it.hasNext()) {
            String item = it.next();
            System.out.println(item);

            if (item.equals("C")) {
                it.remove(); // safe remove during iteration
            }
        }

        System.out.println("After remove: " + list);
    }
}

5) Comparable (Natural Sorting)

  • Comparable is used to define natural order of objects.
  • Implement method: compareTo()
  • Used by Collections.sort() automatically.
import java.util.ArrayList;
import java.util.Collections;

class Student implements Comparable<Student> {
    int roll;
    String name;

    Student(int roll, String name) {
        this.roll = roll;
        this.name = name;
    }

    public int compareTo(Student other) {
        return this.roll - other.roll; // sort by roll (ascending)
    }

    public String toString() {
        return roll + "-" + name;
    }

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student(3, "Sourav"));
        list.add(new Student(1, "Amit"));
        list.add(new Student(2, "Neha"));

        Collections.sort(list); // uses compareTo()
        System.out.println(list);
    }
}

6) Comparator (Custom Sorting)

  • Comparator is used for custom sorting without changing class.
  • Implement method: compare(o1, o2)
  • Useful for multiple sorting options (by name, marks, etc.).
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Student2 {
    int roll;
    String name;

    Student2(int roll, String name) {
        this.roll = roll;
        this.name = name;
    }

    public String toString() {
        return roll + "-" + name;
    }

    public static void main(String[] args) {
        ArrayList<Student2> list = new ArrayList<>();
        list.add(new Student2(3, "Sourav"));
        list.add(new Student2(1, "Amit"));
        list.add(new Student2(2, "Neha"));

        // Sort by name using Comparator
        Collections.sort(list, new Comparator<Student2>() {
            public int compare(Student2 a, Student2 b) {
                return a.name.compareTo(b.name);
            }
        });

        System.out.println("Sorted by name: " + list);
    }
}

7) Quick Notes (Interview Style)

  • List: duplicates allowed + order maintained.
  • Set: unique elements only.
  • Map: key-value pairs, key unique.
  • HashSet/HashMap: fast, no order guarantee.
  • TreeSet/TreeMap: sorted order.
  • Comparable: single natural sorting inside class.
  • Comparator: multiple custom sorting outside class.
⬅ Previous Next ➡