Java Collections Framework Practice Questions with Solutions

The Java Collections Framework (JCF) is a powerful set of classes and interfaces used to store, organize, retrieve, and manipulate groups of objects efficiently. Instead of creating fixed-size arrays, Java developers use collections because they are dynamic, flexible, and provide built-in methods for common operations.

The Collections Framework is one of the most important topics in Core Java and is frequently asked in Java interviews, university exams, and coding assessments. Java Collections Framework practice questions with solutions help to understand the concepts.

For example, collections are used to:

  • Store employee records
  • Manage student information
  • Process customer orders
  • Handle product inventories
  • Build social media applications
  • Develop banking and e-commerce systems

Why Do We Need the Java Collections Framework?

Collections solve many limitations of arrays:

  • Dynamic size (can grow or shrink)
  • Built-in searching and sorting
  • Easy insertion and deletion
  • Better memory management
  • Improved performance
  • Rich utility methods

Collection Hierarchy

                 Iterable
                     │
                Collection
          ┌──────────┼──────────┐
          │          │          │
         List       Set       Queue
          │          │
 ┌────────┼──────┐   ├───────────────┐
 │        │      │   │               │
ArrayList LinkedList Vector HashSet LinkedHashSet TreeSet

Another important interface is:

Map
│
├── HashMap
├── LinkedHashMap
└── TreeMap

Main Interfaces in Collections

  • List
  • Set
  • Queue
  • Map

Common Collection Classes

  • ArrayList
  • LinkedList
  • Vector
  • Stack
  • HashSet
  • LinkedHashSet
  • TreeSet
  • HashMap
  • LinkedHashMap
  • TreeMap

Advantages of Collections

  • Dynamic resizing
  • Built-in algorithms
  • Efficient searching
  • Efficient sorting
  • Easy iteration
  • Reduced coding effort
  • Better performance

Real-World Applications

Java Collections are used in:

  • Banking Software
  • Hospital Management Systems
  • School Management Applications
  • E-commerce Websites
  • Spring Boot Projects
  • Android Apps
  • CRM Software
  • ERP Systems

Before Learning This Chapter

You should already understand:

  • Variables
  • Arrays
  • Classes
  • Objects
  • Methods
  • OOP Concepts
  • File Handling

1. Java Program to Create an ArrayList

Problem Statement

Write a Java program to create an ArrayList and store student names.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

        students.add("Rahul");
        students.add("Amit");
        students.add("Neha");

        System.out.println(students);

    }

}

Sample Output

[Rahul, Amit, Neha]

Explanation

ArrayList is a dynamic collection that automatically increases its size whenever new elements are added.

Unlike arrays, there is no need to specify the size beforehand.

Concepts Covered

  • ArrayList
  • add()
  • Dynamic Array
  • Collections Framework

2. Java Program to Access Elements from an ArrayList

Problem Statement

Write a Java program to access elements stored in an ArrayList.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

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

        System.out.println(cities.get(1));

    }

}

Sample Output

Mumbai

Explanation

The get(index) method returns the element stored at the specified index.

Indexes start from 0.

Concepts Covered

  • ArrayList
  • get()
  • Indexing
  • Collections

3. Java Program to Update an Element in an ArrayList

Problem Statement

Write a Java program to update an existing element in an ArrayList.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

        languages.add("Java");
        languages.add("Python");
        languages.add("C++");

        languages.set(1, "JavaScript");

        System.out.println(languages);

    }

}

Sample Output

[Java, JavaScript, C++]

Explanation

The set(index, value) method replaces the element at the specified index with a new value.

Concepts Covered

  • ArrayList
  • set()
  • Updating Elements
  • Collections Framework

4. Java Program to Remove an Element from an ArrayList

Problem Statement

Write a Java program to remove an element from an ArrayList.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

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

        fruits.remove("Banana");

        System.out.println(fruits);

    }

}

Sample Output

[Apple, Orange]

Explanation

The remove() method removes an element from the ArrayList.

You can remove an element in two ways:

Using the object:

fruits.remove("Banana");

Using the index:

fruits.remove(1);

If the specified element is not found, the list remains unchanged.

Concepts Covered

  • ArrayList
  • remove()
  • Delete Elements
  • Collections Framework

5. Java Program to Find the Size of an ArrayList

Problem Statement

Write a Java program to find the total number of elements stored in an ArrayList.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

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

        System.out.println("Size : " + numbers.size());

    }

}

Sample Output

Size : 4

Explanation

The size() method returns the total number of elements currently stored in the ArrayList.

Unlike arrays, where the size is fixed, an ArrayList can grow or shrink dynamically, and size() always returns the current number of elements.

Concepts Covered

  • ArrayList
  • size()
  • Dynamic Collections
  • Collection Methods

6. Java Program to Iterate Through an ArrayList Using a For Loop

Problem Statement

Write a Java program to display all elements of an ArrayList using a for loop.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

        subjects.add("Java");
        subjects.add("Python");
        subjects.add("SQL");

        for (int i = 0; i < subjects.size(); i++) {

            System.out.println(subjects.get(i));

        }

    }

}

Sample Output

Java
Python
SQL

Explanation

The traditional for loop accesses elements using their index.

The loop starts from index 0 and continues until size() - 1.

This approach is useful when the index is required during processing.

Concepts Covered

  • ArrayList
  • for Loop
  • get()
  • size()

7. Java Program to Iterate Through an ArrayList Using a For-Each Loop

Problem Statement

Write a Java program to display all elements of an ArrayList using a for-each loop.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

        courses.add("Java");
        courses.add("C++");
        courses.add("Python");

        for (String course : courses) {

            System.out.println(course);

        }

    }

}

Sample Output

Java
C++
Python

Explanation

The enhanced for-each loop automatically visits each element of the collection.

It is shorter, cleaner, and easier to read than the traditional for loop when the index is not required.

Concepts Covered

  • Enhanced For Loop
  • ArrayList
  • Collection Traversal
  • Java Collections Framework

8. Java Program to Create and Use a LinkedList

Problem Statement

Write a Java program to create a LinkedList and display its elements.

Java Solution

import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {

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

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

        System.out.println(cities);

    }

}

Sample Output

[Delhi, Mumbai, Jaipur]

Explanation

LinkedList is another implementation of the List interface.

Unlike ArrayList, it stores elements using linked nodes.

It performs better when:

  • Frequent insertions are required.
  • Frequent deletions are required.

Concepts Covered

  • LinkedList
  • add()
  • List Interface
  • Collections Framework

9. Java Program to Create and Use a HashSet

Problem Statement

Write a Java program to create a HashSet and store unique elements.

Java Solution

import java.util.HashSet;

public class Main {

    public static void main(String[] args) {

        HashSet<String> languages = new HashSet<>();

        languages.add("Java");
        languages.add("Python");
        languages.add("Java");
        languages.add("C++");

        System.out.println(languages);

    }

}

Sample Output

[Java, Python, C++]

Note: The order of elements in a HashSet is not guaranteed and may differ each time the program runs.

Explanation

A HashSet stores only unique elements.

If duplicate values are added, they are ignored automatically.

This makes HashSet ideal for removing duplicates from a collection.

Concepts Covered

  • HashSet
  • Unique Elements
  • add()
  • Set Interface

10. Java Program to Create and Use a HashMap

Problem Statement

Write a Java program to create a HashMap and store student IDs with their names.

Java Solution

import java.util.HashMap;

public class Main {

    public static void main(String[] args) {

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

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

        System.out.println(students);

    }

}

Sample Output

{101=Rahul, 102=Amit, 103=Neha}

Explanation

A HashMap stores data as key-value pairs.

  • Keys must be unique.
  • Values can be duplicated.

The put() method inserts data into the map.

HashMap is commonly used for fast searching based on unique keys.

Concepts Covered

  • HashMap
  • put()
  • Key-Value Pairs
  • Map Interface

11. Java Program to Iterate Through a HashMap

Problem Statement

Write a Java program to display all key-value pairs stored in a HashMap.

Java Solution

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

public class Main {

    public static void main(String[] args) {

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

        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

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

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

        }

    }

}

Sample Output

101 : Rahul
102 : Amit
103 : Neha

Explanation

The entrySet() method returns all key-value pairs in the HashMap.

Each pair is represented by a Map.Entry object.

This is the recommended way to iterate through a HashMap.

Concepts Covered

  • HashMap
  • entrySet()
  • Map.Entry
  • For-Each Loop

12. Java Program to Create and Use a TreeSet

Problem Statement

Write a Java program to create a TreeSet and display elements in sorted order.

Java Solution

import java.util.TreeSet;

public class Main {

    public static void main(String[] args) {

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

        numbers.add(50);
        numbers.add(20);
        numbers.add(70);
        numbers.add(10);

        System.out.println(numbers);

    }

}

Sample Output

[10, 20, 50, 70]

Explanation

A TreeSet automatically stores elements in ascending sorted order.

It also removes duplicate elements automatically.

Unlike HashSet, the order of elements is predictable.

Concepts Covered

  • TreeSet
  • Sorted Collection
  • Unique Elements
  • Set Interface

13. Java Program to Create and Use a TreeMap

Problem Statement

Write a Java program to create a TreeMap and display key-value pairs in sorted order.

Java Solution

import java.util.TreeMap;

public class Main {

    public static void main(String[] args) {

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

        students.put(103, "Neha");
        students.put(101, "Rahul");
        students.put(102, "Amit");

        System.out.println(students);

    }

}

Sample Output

{101=Rahul, 102=Amit, 103=Neha}

Explanation

A TreeMap stores key-value pairs in ascending order of keys.

Unlike HashMap, the keys are automatically sorted.

This makes TreeMap useful when ordered data is required.

Concepts Covered

  • TreeMap
  • Sorted Keys
  • Map Interface
  • Key-Value Pairs

14. Java Program to Sort an ArrayList Using Collections.sort()

Problem Statement

Write a Java program to sort an ArrayList in ascending order.

Java Solution

import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String[] args) {

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

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

        Collections.sort(numbers);

        System.out.println(numbers);

    }

}

Sample Output

[10, 20, 30, 50]

Explanation

The Collections.sort() method sorts the elements of an ArrayList in ascending order.

It works with:

  • Integer
  • String
  • Double
  • Custom Objects (using Comparable or Comparator)

Concepts Covered

  • Collections.sort()
  • ArrayList
  • Sorting
  • Collections Utility Class

15. Java Program to Create a Real-World Student Management System Using Collections

Problem Statement

Write a Java program to create a simple student management system using an ArrayList.

Java Solution

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

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

        students.add("Rahul Sharma");
        students.add("Amit Kumar");
        students.add("Neha Singh");

        System.out.println("Student List");

        for (String student : students) {

            System.out.println(student);

        }

    }

}

Sample Output

Student List
Rahul Sharma
Amit Kumar
Neha Singh

Explanation

The program stores student names in an ArrayList and displays them using a for-each loop.

This approach forms the foundation of many real-world systems such as:

  • Student Management Systems
  • Employee Management Software
  • Customer Management Applications
  • Inventory Systems

Collections make it easy to add, remove, search, and update records dynamically.

Concepts Covered

  • ArrayList
  • For-Each Loop
  • Dynamic Data Storage
  • Real-World Collections Usage

Chapter Summary

In this chapter, you learned the Java Collections Framework (JCF), one of the most powerful and widely used features in Java. The Collections Framework provides ready-made classes and interfaces that make it easier to store, organize, search, update, and manipulate groups of objects efficiently.

You explored different collection types such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, and TreeMap, along with their real-world applications. You also learned how to iterate through collections, sort data, and build a simple student management system using collections.

Throughout this chapter, you covered:

  • Introduction to Java Collections Framework
  • Collection Hierarchy
  • List Interface
  • Set Interface
  • Map Interface
  • ArrayList
  • LinkedList
  • HashSet
  • TreeSet
  • HashMap
  • TreeMap
  • Collections.sort()
  • Iterating Through Collections
  • Student Management System Example

These concepts are extensively used in enterprise applications, Spring Boot projects, Android development, web applications, and software systems that manage large amounts of data.


Key Takeaways

  • Java Collections Framework provides dynamic data structures.
  • ArrayList stores ordered, dynamic elements.
  • LinkedList is efficient for frequent insertions and deletions.
  • HashSet stores only unique elements.
  • TreeSet stores unique elements in sorted order.
  • HashMap stores data as key-value pairs.
  • TreeMap stores key-value pairs sorted by keys.
  • Collections.sort() sorts lists in ascending order.
  • Collections provide built-in methods for searching, sorting, updating, and removing data.
  • Choosing the correct collection improves application performance and maintainability.

Frequently Asked Questions (FAQs)

1. What is the Java Collections Framework?

The Java Collections Framework (JCF) is a set of interfaces and classes used to store, manage, and manipulate groups of objects dynamically.


2. What is the difference between an Array and an ArrayList?

ArrayArrayList
Fixed sizeDynamic size
Stores primitives and objectsStores objects only (primitive values use wrapper classes)
Fewer built-in methodsRich built-in methods

3. What is the difference between ArrayList and LinkedList?

ArrayListLinkedList
Faster random accessFaster insertion and deletion
Uses dynamic arrayUses doubly linked list
Better for searchingBetter for frequent modifications

4. What is the difference between HashSet and TreeSet?

HashSetTreeSet
No guaranteed orderStores elements in sorted order
FasterSlightly slower due to sorting
Removes duplicatesRemoves duplicates

5. What is the difference between HashMap and TreeMap?

HashMapTreeMap
Unordered keysSorted keys
FasterSlightly slower
Allows one null keyDoes not allow null keys

6. What is the purpose of Collections.sort()?

Collections.sort() sorts the elements of a list in ascending order.

Example:

Collections.sort(numbers);

It can sort:

  • Integer
  • String
  • Double
  • Custom Objects (using Comparable or Comparator)

7. When should you use a HashMap?

Use a HashMap when:

  • Fast searching is required.
  • Data is stored as key-value pairs.
  • The order of keys is not important.

Common examples:

  • Student Records
  • Employee IDs
  • Product Catalogs
  • Customer Databases

8. Where is the Java Collections Framework used in real-world applications?

The Java Collections Framework is widely used in:

  • Banking Applications
  • E-commerce Websites
  • Hospital Management Systems
  • School Management Software
  • Inventory Systems
  • CRM Applications
  • ERP Software
  • Android Applications
  • Spring Boot Projects
  • Enterprise Java Applications

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top