Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Collections Framework

The Java Collections Framework (JCF) provides a set of predefined classes and interfaces to store, manipulate, and retrieve groups of objects efficiently. Instead of handling arrays manually, collections offer dynamic sizing, built-in algorithms, and high performance. Collections are widely used in enterprise applications, interviews, and real-world projects.


1. Collection Hierarchy

At the top of the hierarchy is the Collection interface, which is part of java.util package.

Iterable
   ↓
Collection
   ├── List
   ├── Set
   └── Queue
Map (separate hierarchy)

Key Points

  • Collection is the root interface for List, Set, and Queue
  • Map does not extend Collection
  • All collections store objects only (wrapper classes for primitives)

2. List Interface

Description

A List is an ordered collection that allows:

  • Duplicate elements
  • Index-based access
  • Insertion order preservation

2.1 ArrayList

Characteristics

  • Dynamic array
  • Fast random access
  • Slower insertion/deletion in the middle

Example

import java.util.*;

public class Demo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("Java"); // duplicates allowed

        System.out.println(list);
    }
}

2.2 LinkedList

Characteristics

  • Doubly linked list
  • Faster insertion and deletion
  • Slower access than ArrayList

Example

LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(10);
numbers.add(20);
numbers.addFirst(5);

System.out.println(numbers);

2.3 Vector

Characteristics

  • Synchronized (thread-safe)
  • Slower than ArrayList
  • Legacy class

Example

Vector<String> v = new Vector<>();
v.add("A");
v.add("B");
System.out.println(v);

3. Set Interface

Description

A Set stores unique elements only and does not allow duplicates.


3.1 HashSet

Characteristics

  • No duplicate elements
  • No order maintained
  • Fast performance

Example

HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple");

System.out.println(set);

3.2 LinkedHashSet

Characteristics

  • Maintains insertion order
  • No duplicates

Example

LinkedHashSet<Integer> lhs = new LinkedHashSet<>();
lhs.add(10);
lhs.add(5);
lhs.add(20);

System.out.println(lhs);

3.3 TreeSet

Characteristics

  • Stores elements in sorted order
  • No duplicates
  • Slower than HashSet

Example

TreeSet<Integer> ts = new TreeSet<>();
ts.add(30);
ts.add(10);
ts.add(20);

System.out.println(ts);

4. Map Interface

Description

A Map stores data in key-value pairs.

  • Keys must be unique
  • Values can be duplicated

4.1 HashMap

Characteristics

  • No order maintained
  • Allows one null key
  • Fast performance

Example

HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");

System.out.println(map);

4.2 LinkedHashMap

Characteristics

  • Maintains insertion order

Example

LinkedHashMap<Integer, String> lhm = new LinkedHashMap<>();
lhm.put(1, "A");
lhm.put(2, "B");

System.out.println(lhm);

4.3 TreeMap

Characteristics

  • Sorted by keys
  • No null keys

Example

TreeMap<Integer, String> tm = new TreeMap<>();
tm.put(3, "C");
tm.put(1, "A");
tm.put(2, "B");

System.out.println(tm);

5. Queue and Deque

Queue Interface

Description

  • Follows FIFO (First In First Out)

Example

Queue<Integer> q = new LinkedList<>();
q.add(10);
q.add(20);
q.poll();

System.out.println(q);

Deque Interface

Description

  • Allows insertion and deletion at both ends

Example

Deque<Integer> dq = new ArrayDeque<>();
dq.addFirst(10);
dq.addLast(20);

System.out.println(dq);

6. Iterators and Enhanced For Loop

Iterator

Used to traverse collections safely.

Example

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

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

Enhanced For Loop

Simpler way to iterate.

Example

for (String lang : list) {
    System.out.println(lang);
}

7. Comparable and Comparator

Comparable Interface

Used for natural sorting order.

Example

class Student implements Comparable<Student> {
    int age;
    Student(int age) {
        this.age = age;
    }

    public int compareTo(Student s) {
        return this.age - s.age;
    }
}

Comparator Interface

Used for custom sorting logic.

Example

Comparator<Student> ageComparator = new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s2.age - s1.age;
    }
};

Comparable vs Comparator

ComparableComparator
Natural sortingCustom sorting
compareTo()compare()
One sorting logicMultiple sorting logics

Example:

java

import java.util.*;

class Person implements Comparable<Person> {
    String name;
    int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public int compareTo(Person other) {
        return this.age - other.age;
    }
    
    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class CollectionsDemo {
    public static void main(String[] args) {
        // ArrayList
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        System.out.println("Fruits: " + fruits);
        
        // HashSet (no duplicates)
        Set<Integer> numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(10);  // Duplicate, won't be added
        System.out.println("Numbers: " + numbers);
        
        // HashMap
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 95);
        scores.put("Bob", 87);
        scores.put("Charlie", 92);
        
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        
        // TreeSet (sorted)
        Set<Person> people = new TreeSet<>();
        people.add(new Person("John", 30));
        people.add(new Person("Alice", 25));
        people.add(new Person("Bob", 35));
        System.out.println("People sorted by age: " + people);
        
        // Queue
        Queue<String> queue = new LinkedList<>();
        queue.offer("First");
        queue.offer("Second");
        queue.offer("Third");
        System.out.println("Queue poll: " + queue.poll());
        
        // Sorting with Comparator
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("John", 30));
        personList.add(new Person("Alice", 25));
        
        Collections.sort(personList, (p1, p2) -> p1.name.compareTo(p2.name));
        System.out.println("Sorted by name: " + personList);
    }
}

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥