allizwell.jobsdoor360.in

Java Collections Framework

Java Programming Course › Module 07: Java Collections Framework
JAVA PROGRAMMING / MODULE 07

Java Collections Framework

Learn how to store and manage groups of data using ArrayList, LinkedList, HashSet, TreeSet, HashMap and other useful collection classes in Java.

Beginner Friendly Placement Preparation 9 Topics

Introduction to This Module

Imagine you want to store the names of 100 students. You could create 100 separate variables, but that would make your program difficult to manage.

Instead, Java provides collection classes that allow us to store multiple values together and perform operations such as adding, removing, searching and sorting elements.

The Java Collections Framework is a group of interfaces and classes designed to make working with collections of objects easier.

What You Will Learn

  • Understand the Java Collections Framework.
  • Learn the difference between List, Set and Map.
  • Store and access elements using ArrayList.
  • Understand LinkedList and its common operations.
  • Remove duplicate values using HashSet and TreeSet.
  • Store key-value pairs using HashMap and TreeMap.
  • Traverse collections using Iterator and ListIterator.
  • Sort objects using Comparable and Comparator.
  • Use common methods of the Collections utility class.
TOPIC 01

1. Introduction to the Java Collections Framework

What Is a Collection?

A collection is simply a group of objects stored together. For example, a list of student names, a set of unique roll numbers or a collection of product prices.

Why Do We Need Collections?

Arrays are useful for storing multiple values, but they have a fixed size. Once an array is created, its size cannot be changed.

Collections provide more flexibility. Many collection classes can grow or shrink as elements are added or removed.

Real-Life Example

Imagine a shopping list. You may add new items, remove items you no longer need, or check whether a particular item is already present.

Java collections provide methods that make these operations easier.

Collections Framework Structure

The main collection interfaces include List, Set and Queue. Map is also part of the Java Collections Framework, but it is separate from the Collection interface.

Interface Purpose Example Classes
List Stores elements in sequence and allows duplicates. ArrayList, LinkedList
Set Stores unique elements without duplicates. HashSet, TreeSet
Queue Stores elements for processing, often in a particular order. PriorityQueue, LinkedList
Map Stores data as key-value pairs. HashMap, TreeMap

Basic Collection Operations

Most collection classes provide methods such as:

  • add() – Adds an element.
  • remove() – Removes an element.
  • contains() – Checks whether an element exists.
  • size() – Returns the number of elements.
  • clear() – Removes all elements.
  • isEmpty() – Checks whether the collection is empty.

Why Do We Use Generics?

Generics allow us to specify the type of data that a collection can store. For example, ArrayList<String> stores String values.

Java Code
import java.util.ArrayList;

class Main {

    public static void main(String[] args) {

        ArrayList<String> names = new ArrayList<>();

        names.add("Aman");
        names.add("Riya");
        names.add("Rahul");

        System.out.println(names);

    }
}
Output:
[Aman, Riya, Rahul]
Remember: List, Set and Queue extend the Collection interface. Map is a separate interface and does not extend Collection.
TOPIC 02

2. ArrayList

What Is an ArrayList?

ArrayList is a resizable collection that stores elements in a sequence. Unlike a normal array, its size can grow or shrink when elements are added or removed.

It belongs to the List interface and allows duplicate elements.

Creating an ArrayList

Java Syntax
import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();

Common ArrayList Methods

Method Purpose
add(element) Adds an element.
get(index) Returns the element at an index.
set(index, element) Replaces an element at an index.
remove(index) Removes the element at an index.
size() Returns the number of elements.
contains(element) Checks whether an element exists.

Example: Adding and Accessing Elements

Java Code
import java.util.ArrayList;

class Main {

    public static void main(String[] args) {

        ArrayList<String> names = new ArrayList<>();

        names.add("Aman");
        names.add("Riya");
        names.add("Rahul");

        System.out.println(names);

        System.out.println("First name: " + names.get(0));

        System.out.println("Total names: " + names.size());

    }
}
Output:
[Aman, Riya, Rahul]
First name: Aman
Total names: 3

Example: Updating and Removing Elements

Java Code
import java.util.ArrayList;

class Main {

    public static void main(String[] args) {

        ArrayList<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");

        fruits.set(1, "Orange");

        fruits.remove("Banana");

        System.out.println(fruits);

    }
}
Output:
[Apple, Orange]

Traversing an ArrayList

Traversing means visiting each element one by one. We can use a normal for loop or an enhanced for loop.

Java Code
import java.util.ArrayList;

class Main {

    public static void main(String[] args) {

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

        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        for (int number : numbers) {

            System.out.println(number);

        }

    }
}
Output:
10
20
30

Important Points About ArrayList

  • Maintains insertion order.
  • Allows duplicate elements.
  • Allows null elements.
  • Provides fast access using an index.
  • Adding or removing elements in the middle may require shifting other elements.
  • It is not synchronized by default.
Placement Tip: ArrayList is a common interview topic. Remember that it maintains insertion order, allows duplicates and provides index-based access.
TOPIC 03

3. LinkedList

What Is a LinkedList?

LinkedList is a collection in which elements are stored as connected nodes. Each node contains data and links to other nodes.

Java's LinkedList class is a doubly linked list. Each node is connected to both the previous and next nodes.

Simple Example

Imagine a train. Each coach is connected to the coach before it and the coach after it.

A doubly linked list works in a similar way. Each node stores a value and links to its neighbouring nodes.

Basic Structure

Conceptual Representation
NULL <- [10] <-> [20] <-> [30] -> NULL

Each node contains:
1. Data
2. Link to previous node
3. Link to next node

Creating a LinkedList

Java Syntax
import java.util.LinkedList;

LinkedList<String> names = new LinkedList<>();

Example: Adding and Removing Elements

Java Code
import java.util.LinkedList;

class Main {

    public static void main(String[] args) {

        LinkedList<String> cities = new LinkedList<>();

        cities.add("Delhi");
        cities.add("Mumbai");
        cities.add("Jaipur");

        cities.addFirst("Jodhpur");
        cities.addLast("Pune");

        System.out.println(cities);

        cities.removeFirst();
        cities.removeLast();

        System.out.println(cities);

    }
}
Output:
[Delhi, Mumbai, Jaipur, Jodhpur, Pune]
[Mumbai, Jaipur, Jodhpur]

The first output shows the elements after adding values at both ends. The second output shows the list after removing the first and last elements.

Common LinkedList Methods

Method Purpose
addFirst() Adds an element at the beginning.
addLast() Adds an element at the end.
removeFirst() Removes the first element.
removeLast() Removes the last element.
getFirst() Returns the first element.
getLast() Returns the last element.

ArrayList vs LinkedList

ArrayList LinkedList
Uses a resizable array internally. Uses a doubly linked list internally.
Fast index-based access. Index-based access requires traversal.
Middle insertions and removals may require shifting elements. Once a node is reached, linking changes can be efficient.
Usually uses less memory per element. Needs extra memory for node links.
Good for frequent reading by index. Useful for operations at the ends and list-based processing.
Remember: LinkedList is not automatically faster than ArrayList for every insertion or deletion. Finding the position may itself require traversal.
TOPIC 04

4. HashSet and TreeSet

What Is a Set?

A Set is a collection that does not allow duplicate elements. If you try to add the same value more than once, it is stored only once.

A. HashSet

HashSet stores unique elements using a hashing mechanism. It does not guarantee the order in which elements are displayed.

Example: Using HashSet

Java Code
import java.util.HashSet;

class Main {

    public static void main(String[] args) {

        HashSet<Integer> numbers = new HashSet<>();

        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(20);

        System.out.println(numbers);

        System.out.println(numbers.contains(10));

    }
}
Possible Output:
[20, 10, 30]
true

The order of HashSet elements is not guaranteed. Your output may show a different order.

B. TreeSet

TreeSet stores unique elements in sorted order. By default, elements are arranged in ascending order.

Example: Using TreeSet

Java Code
import java.util.TreeSet;

class Main {

    public static void main(String[] args) {

        TreeSet<Integer> numbers = new TreeSet<>();

        numbers.add(40);
        numbers.add(10);
        numbers.add(30);
        numbers.add(20);
        numbers.add(10);

        System.out.println(numbers);

    }
}
Output:
[10, 20, 30, 40]

HashSet vs TreeSet

HashSet TreeSet
Does not guarantee iteration order. Stores elements in sorted order.
Uses hashing. Uses a tree-based structure.
Usually offers average constant-time basic operations. Basic operations generally take logarithmic time.
Allows one null element. Normally does not allow null with natural ordering.
Placement Tip: If the question asks for unique elements without a required order, consider HashSet. If unique elements must be sorted, consider TreeSet.
TOPIC 05

5. HashMap and TreeMap

What Is a Map?

A Map stores information in key-value pairs. Each key is unique and is used to access its corresponding value.

Real-Life Example

Imagine a school record system. Each student has a unique roll number and a name.

The roll number acts as the key, and the student's name acts as the value.

A. HashMap

HashMap stores key-value pairs using hashing. It does not guarantee the order in which entries are returned.

Example: Using HashMap

Java Code
import java.util.HashMap;

class Main {

    public static void main(String[] args) {

        HashMap<Integer, String> students = new HashMap<>();

        students.put(101, "Aman");
        students.put(102, "Riya");
        students.put(103, "Rahul");

        System.out.println(students);

        System.out.println(students.get(102));

    }
}
Possible Output:
{101=Aman, 102=Riya, 103=Rahul}
Riya

The order of HashMap entries is not guaranteed.

Important HashMap Methods

Method Purpose
put(key, value) Adds or updates a key-value pair.
get(key) Returns the value associated with a key.
remove(key) Removes an entry using its key.
containsKey(key) Checks whether a key exists.
containsValue(value) Checks whether a value exists.
keySet() Returns a Set of all keys.
values() Returns a collection of all values.

Traversing a HashMap

Java Code
import java.util.HashMap;
import java.util.Map;

class Main {

    public static void main(String[] args) {

        HashMap<Integer, String> students = new HashMap<>();

        students.put(101, "Aman");
        students.put(102, "Riya");
        students.put(103, "Rahul");

        for (Map.Entry<Integer, String> entry
                : students.entrySet()) {

            System.out.println(
                entry.getKey() + " : " + entry.getValue()
            );

        }

    }
}
Possible Output:
101 : Aman
102 : Riya
103 : Rahul

HashMap does not guarantee this order. The entries may appear in a different order.

B. TreeMap

TreeMap stores key-value pairs in sorted order of keys. By default, keys are arranged in ascending order.

Example: Using TreeMap

Java Code
import java.util.TreeMap;

class Main {

    public static void main(String[] args) {

        TreeMap<Integer, String> students = new TreeMap<>();

        students.put(103, "Rahul");
        students.put(101, "Aman");
        students.put(102, "Riya");

        System.out.println(students);

    }
}
Output:
{101=Aman, 102=Riya, 103=Rahul}

HashMap vs TreeMap

HashMap TreeMap
Does not guarantee entry order. Sorts entries by keys.
Uses hashing. Uses a tree-based structure.
Usually offers average constant-time basic operations. Basic operations generally take logarithmic time.
Allows one null key and null values. Normally does not allow null keys with natural ordering; null values are allowed.
Remember: A Map cannot contain duplicate keys. If you insert a value using a key that already exists, the old value is replaced.
TOPIC 06

6. Iterator and ListIterator

What Is an Iterator?

An Iterator is an object used to visit elements of a collection one by one.

It is useful when we want to process each element without using an index.

Common Iterator Methods

Method Purpose
hasNext() Checks whether another element is available.
next() Returns the next element.
remove() Removes the last element returned by the iterator, when supported.

Example: Using Iterator

Java Code
import java.util.ArrayList;
import java.util.Iterator;

class Main {

    public static void main(String[] args) {

        ArrayList<String> names = new ArrayList<>();

        names.add("Aman");
        names.add("Riya");
        names.add("Rahul");

        Iterator<String> it = names.iterator();

        while (it.hasNext()) {

            System.out.println(it.next());

        }

    }
}
Output:
Aman
Riya
Rahul

What Is ListIterator?

ListIterator is used with List collections. Unlike a normal Iterator, it can move both forward and backward.

Example: Using ListIterator

Java Code
import java.util.ArrayList;
import java.util.ListIterator;

class Main {

    public static void main(String[] args) {

        ArrayList<String> names = new ArrayList<>();

        names.add("Aman");
        names.add("Riya");
        names.add("Rahul");

        ListIterator<String> it = names.listIterator();

        System.out.println("Forward:");

        while (it.hasNext()) {
            System.out.println(it.next());
        }

        System.out.println("Backward:");

        while (it.hasPrevious()) {
            System.out.println(it.previous());
        }

    }
}
Output:
Forward:
Aman
Riya
Rahul
Backward:
Rahul
Riya
Aman

Iterator vs ListIterator

Iterator ListIterator
Can move forward. Can move forward and backward.
Works with collections that provide an iterator. Works only with List implementations.
Can remove elements when supported. Can remove, replace and add elements when supported.
Placement Tip: Remember that Iterator moves forward, while ListIterator can move in both directions.
TOPIC 07

7. Comparable and Comparator

Why Do We Need Comparable and Comparator?

Suppose you have a list of students. Each student has a name and marks. You may want to sort the students by their marks or by their names.

Java provides Comparable and Comparator to define how objects should be compared and sorted.

A. Comparable

Comparable is an interface used when a class defines its own natural ordering.

It provides the compareTo() method.

Example: Sorting Students by Marks

Java Code
import java.util.ArrayList;
import java.util.Collections;

class Student implements Comparable<Student> {

    int marks;

    Student(int marks) {
        this.marks = marks;
    }

    public int compareTo(Student other) {

        return this.marks - other.marks;

    }
}

class Main {

    public static void main(String[] args) {

        ArrayList<Student> students = new ArrayList<>();

        students.add(new Student(80));
        students.add(new Student(60));
        students.add(new Student(90));

        Collections.sort(students);

        for (Student s : students) {

            System.out.println(s.marks);

        }

    }
}
Output:
60
80
90

B. Comparator

Comparator is used when we want to define a separate comparison rule. It is especially useful when we need different sorting orders for the same class.

Example: Sorting Students Using Comparator

Java Code
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Student {

    int marks;

    Student(int marks) {
        this.marks = marks;
    }
}

class Main {

    public static void main(String[] args) {

        ArrayList<Student> students = new ArrayList<>();

        students.add(new Student(80));
        students.add(new Student(60));
        students.add(new Student(90));

        Comparator<Student> byMarks =
            new Comparator<Student>() {

                public int compare(Student a, Student b) {

                    return Integer.compare(a.marks, b.marks);

                }
            };

        Collections.sort(students, byMarks);

        for (Student s : students) {

            System.out.println(s.marks);

        }

    }
}
Output:
60
80
90

Comparable vs Comparator

Comparable Comparator
Defines natural ordering for a class. Defines a separate comparison rule.
Uses compareTo(). Uses compare().
Implemented by the class being compared. Can be implemented in a separate class or created separately.
Usually represents the class's default sorting order. Allows multiple sorting rules.
Remember: Comparable uses compareTo(), while Comparator uses compare().
TOPIC 08

8. Collections Utility Class

What Is the Collections Class?

Java provides a utility class called Collections. It contains useful static methods for working with collections.

It is different from the Collection interface:

  • Collection: An interface representing a group of objects.
  • Collections: A utility class containing helpful methods for collections.

Common Collections Methods

Method Purpose
sort() Sorts a list.
reverse() Reverses the order of a list.
shuffle() Randomly rearranges list elements.
max() Returns the maximum element.
min() Returns the minimum element.
frequency() Counts occurrences of an element.

Example: Sorting and Reversing a List

Java Code
import java.util.ArrayList;
import java.util.Collections;

class Main {

    public static void main(String[] args) {

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

        numbers.add(40);
        numbers.add(10);
        numbers.add(30);
        numbers.add(20);

        Collections.sort(numbers);

        System.out.println("Sorted: " + numbers);

        Collections.reverse(numbers);

        System.out.println("Reversed: " + numbers);

        System.out.println("Maximum: "
                + Collections.max(numbers));

        System.out.println("Minimum: "
                + Collections.min(numbers));

    }
}
Output:
Sorted: [10, 20, 30, 40]
Reversed: [40, 30, 20, 10]
Maximum: 40
Minimum: 10

Example: Counting an Element

Java Code
import java.util.ArrayList;
import java.util.Collections;

class Main {

    public static void main(String[] args) {

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

        numbers.add(10);
        numbers.add(20);
        numbers.add(10);
        numbers.add(30);
        numbers.add(10);

        int count = Collections.frequency(numbers, 10);

        System.out.println("10 appears " + count + " times.");

    }
}
Output:
10 appears 3 times.
Remember: Collections is a utility class. Its methods are commonly used with List objects, and some methods also work with other collection types.
TOPIC 09

9. Important Differences and Interview Questions

Quick Comparison of Common Collection Classes

Class Duplicates Ordering Stores
ArrayList Allowed Insertion order Elements
LinkedList Allowed Insertion order Elements
HashSet Not allowed No guaranteed order Unique elements
TreeSet Not allowed Sorted order Unique elements
HashMap Keys are unique No guaranteed order Key-value pairs
TreeMap Keys are unique Sorted by keys Key-value pairs

Important Interview Questions

Q1. What is the Java Collections Framework?

It is a group of interfaces and classes that provides ready-made ways to store and manipulate groups of objects.

Q2. What is the difference between Collection and Collections?

Collection is an interface, while Collections is a utility class that provides static methods such as sort(), reverse() and max().

Q3. What is the difference between List and Set?

List maintains an ordered sequence and allows duplicates. Set stores unique elements and does not allow duplicates.

Q4. What is the difference between ArrayList and LinkedList?

ArrayList uses a resizable array and provides fast index-based access. LinkedList uses a doubly linked list and supports efficient operations at its ends.

Q5. Does ArrayList allow duplicate elements?

Yes. ArrayList allows duplicate elements.

Q6. Does HashSet allow duplicate elements?

No. HashSet stores unique elements. Adding an existing element does not create another entry.

Q7. What is the difference between HashSet and TreeSet?

HashSet does not guarantee iteration order, while TreeSet stores elements in sorted order.

Q8. What is a HashMap?

HashMap is a Map implementation that stores data as key-value pairs and does not guarantee entry order.

Q9. Can a HashMap contain duplicate keys?

No. Each key is unique. Adding a value with an existing key replaces the previous value.

Q10. What is the difference between HashMap and TreeMap?

HashMap does not guarantee entry order, while TreeMap sorts entries according to their keys.

Q11. What is an Iterator?

Iterator is an object used to visit collection elements one by one.

Q12. What is the difference between Iterator and ListIterator?

Iterator moves forward, while ListIterator can move both forward and backward through a List.

Q13. What is Comparable?

Comparable is an interface used by a class to define its natural ordering through compareTo().

Q14. What is Comparator?

Comparator is an interface used to define a separate comparison rule through compare().

Q15. What is the difference between Comparable and Comparator?

Comparable defines the natural ordering of a class. Comparator allows separate or multiple sorting rules.

Q16. Can we store different data types in an ArrayList?

A raw ArrayList can store different object types, but using generics such as ArrayList<String> is recommended for type safety.

Q17. Is HashMap synchronized?

No. HashMap is not synchronized by default.

Q18. Can HashSet store null?

Yes. HashSet allows one null element.

Module Summary

  • The Collections Framework helps store and manage groups of objects.
  • List allows duplicates and maintains an ordered sequence.
  • ArrayList uses a resizable array.
  • LinkedList uses a doubly linked list.
  • Set stores unique elements.
  • HashSet does not guarantee iteration order.
  • TreeSet stores unique elements in sorted order.
  • Map stores data as key-value pairs.
  • HashMap does not guarantee entry order.
  • TreeMap sorts entries according to their keys.
  • Iterator is used to traverse collection elements.
  • Comparable and Comparator define object comparison rules.
  • Collections provides useful utility methods such as sort(), reverse(), min() and max().

Practice Questions

Write these programs yourself to strengthen your understanding of the Java Collections Framework.

  1. Create an ArrayList of five student names and display them.
  2. Write a program to add, update and remove elements from an ArrayList.
  3. Write a program to find whether a number exists in an ArrayList.
  4. Create a LinkedList and add elements at the beginning and end.
  5. Write a program to remove duplicate numbers using HashSet.
  6. Store numbers in a TreeSet and display them in sorted order.
  7. Create a HashMap to store student roll numbers and names.
  8. Write a program to count the frequency of each number using a HashMap.
  9. Traverse an ArrayList using Iterator.
  10. Sort a list of integers using Collections.sort().
  11. Create a Student class and sort students using Comparable.
  12. Sort student objects using Comparator.

Congratulations! Module 07 Completed

You have learned how to store, access, search, remove and sort data using the Java Collections Framework. You now understand the important differences between List, Set and Map and their commonly used implementations.

Collections are frequently used in Java programming assignments, coding rounds and technical interviews. Practise the examples before moving to the next module.

Scroll to Top