Top 5 Java Collections Coding Interview Questions and Solutions (Core Java + Java 8) – Part 3

Introduction :

The Java Collections Framework (JCF) is one of the most fundamental and widely used components of Java programming. It provides a set of interfaces and classes that help developers efficiently store, organize, search, update, and manipulate groups of objects. Whether you're developing a simple console application or building enterprise-level applications using Spring Boot and Microservices, collections play a vital role in managing application data.

Because of their importance in real-world software development, Java Collections are among the most frequently tested topics in technical interviews. Interviewers often ask coding questions involving List, Set, Map, Queue, and Comparator to evaluate a candidate's understanding of data structures, problem-solving skills, and knowledge of the Java Collections Framework. A strong understanding of these concepts not only helps you crack interviews but also enables you to write cleaner, more efficient, and maintainable code.

In this article, we'll explore five of the most commonly asked Java Collections coding interview questions using both Core Java and Java 8 Streams (where applicable).Interviewer's Follow-up Questions





Whether you're preparing for Java Developer, Spring Boot Developer, or Java Full Stack Developer interviews, this article will strengthen your understanding of the Java Collections Framework and help you solve interview coding problems with confidence.

Let's get started!


Problem 1: Remove Duplicate Elements from a List While Preserving Insertion Order

Difficulty Level : 🟢 Easy


Interview Question

Write a Java program to remove duplicate elements from a List<Integer> while preserving the insertion order. Solve the problem using both Core Java and Java 8 Streams.


Problem Statement

Given a list of integers, remove all duplicate elements and return a new list containing only unique elements. The order of the first occurrence of each element must remain unchanged.

This is one of the most frequently asked Java Collections interview questions because it tests your understanding of the differences between List and Set, as well as your knowledge of the Java Collections Framework.


Example

Input

[10, 20, 30, 20, 40, 10, 50]

Output

[10, 20, 30, 40, 50]

Solution 1 – Core Java

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

public class RemoveDuplicateElements {

    public static void main(String[] args) {

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

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

        List<Integer> uniqueNumbers = new ArrayList<>(
                new LinkedHashSet<>(numbers));

        System.out.println("Original List : " + numbers);
        System.out.println("Unique List   : " + uniqueNumbers);
    }
}

Output

Original List : [10, 20, 30, 20, 40, 10, 50]
Unique List   : [10, 20, 30, 40, 50]

Solution 2 – Java 8 Streams

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveDuplicateUsingStreams {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(
                10, 20, 30, 20, 40, 10, 50);

        List<Integer> uniqueNumbers = numbers.stream()
                                             .distinct()
                                             .collect(Collectors.toList());

        System.out.println("Original List : " + numbers);
        System.out.println("Unique List   : " + uniqueNumbers);
    }
}

Output

Original List : [10, 20, 30, 20, 40, 10, 50]
Unique List   : [10, 20, 30, 40, 50]

Dry Run

Let's understand how the algorithm works step by step.

Input List

[10, 20, 30, 20, 40, 10, 50]

Step-by-Step Execution

StepElementAlready Exists?Result
110No[10]
220No[10, 20]
330No[10, 20, 30]
420Yes[10, 20, 30]
540No[10, 20, 30, 40]
610Yes[10, 20, 30, 40]
750No[10, 20, 30, 40, 50]

Final Output

[10, 20, 30, 40, 50]

Explanation

A List in Java allows duplicate elements while preserving insertion order. However, when we need only unique elements, we should use a Set, as it automatically removes duplicates.

In the Core Java solution, we use a LinkedHashSet. Unlike HashSet, LinkedHashSet preserves the insertion order while eliminating duplicate values. By passing the list to the LinkedHashSet constructor, duplicate elements are automatically removed. We then convert the set back into a List because many applications require the result in list form.

In the Java 8 Stream solution, we use the distinct() method. This intermediate stream operation removes duplicate elements while preserving the encounter order of the stream. Finally, Collectors.toList() converts the stream back into a list.

Both approaches have a time complexity of O(n) and are efficient for most interview scenarios. The Stream solution is more concise and modern, while the LinkedHashSet approach demonstrates a solid understanding of the Java Collections Framework.

Problem 2: Find the Frequency of Each Element in a List

Difficulty Level : 🟢 Easy to Medium


Interview Question

Write a Java program to count the frequency of each element in a List using both Core Java and Java 8 Streams.


Problem Statement

Given a list of integers, count how many times each element appears and display the frequency of every unique element.

This question is one of the most frequently asked Java Collections interview questions because it evaluates your understanding of List, Map, iteration, and the Java 8 Stream API. It also helps interviewers assess your ability to work with key-value pairs efficiently.


📥 Example

Input

[10, 20, 10, 30, 20, 10, 40]

Output

10 -> 3
20 -> 2
30 -> 1
40 -> 1

💻 Solution 1 – Core Java

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class FrequencyOfElements {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(
                10, 20, 10, 30, 20, 10, 40);

        Map<Integer, Integer> frequencyMap = new LinkedHashMap<>();

        for (Integer number : numbers) {
            frequencyMap.put(number,
                    frequencyMap.getOrDefault(number, 0) + 1);
        }

        System.out.println("Element Frequency");

        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}

Output

Element Frequency

10 -> 3
20 -> 2
30 -> 1
40 -> 1

🌊 Solution 2 – Java 8 Streams

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FrequencyUsingStreams {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(
                10, 20, 10, 30, 20, 10, 40);

        Map<Integer, Long> frequencyMap = numbers.stream()
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        LinkedHashMap::new,
                        Collectors.counting()));

        frequencyMap.forEach((key, value) ->
                System.out.println(key + " -> " + value));
    }
}

Output

10 -> 3
20 -> 2
30 -> 1
40 -> 1

Dry Run

Input

[10, 20, 10, 30, 20, 10, 40]

Step-by-Step Execution

StepCurrent ElementMap Content
110{10=1}
220{10=1, 20=1}
310{10=2, 20=1}
430{10=2, 20=1, 30=1}
520{10=2, 20=2, 30=1}
610{10=3, 20=2, 30=1}
740{10=3, 20=2, 30=1, 40=1}

Final Output

10 -> 3
20 -> 2
30 -> 1
40 -> 1

Explanation

A List allows duplicate elements, making it suitable for storing repeated values. However, when we need to count how many times each element appears, a Map is the most appropriate data structure because it stores data as key-value pairs.

In the Core Java solution, we use a LinkedHashMap to maintain the insertion order of elements. We iterate through each element in the list and use the getOrDefault() method to retrieve the current count. If the element is not already present in the map, getOrDefault() returns 0. We then increment the count by one and update the map.

In the Java 8 Stream solution, we use the powerful Collectors.groupingBy() method along with Collectors.counting(). The Function.identity() method uses each element itself as the key, while LinkedHashMap::new ensures that the original insertion order is preserved. This approach is concise, expressive, and commonly used in modern Java applications.

Both approaches efficiently count the frequency of elements and have a time complexity of O(n), making them suitable for large datasets and interview coding challenges.

Problem 3: Sort a List of Employees by Salary

Difficulty Level : 🟡 Medium


Interview Question

Write a Java program to sort a list of employees based on their salary in ascending order using both Core Java and Java 8 Streams.


Problem Statement

Given a list of employees, where each employee has an ID, Name, and Salary, sort the employees in ascending order of salary.

This question evaluates your understanding of Comparator, Collections.sort(), Stream.sorted(), and sorting custom objects using the Java Collections Framework.


📥 Example

Input

Employee IDNameSalary
101Alice65000
102Bob45000
103Charlie85000
104David55000

Output

Employee IDNameSalary
102Bob45000
104David55000
101Alice65000
103Charlie85000

💻 Solution 1 – Core Java

import java.util.*;

class Employee {

    private int id;
    private String name;
    private double salary;

    public Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return id + " - " + name + " - ₹" + salary;
    }
}

public class SortEmployees {

    public static void main(String[] args) {

        List<Employee> employees = new ArrayList<>();

        employees.add(new Employee(101, "Alice", 65000));
        employees.add(new Employee(102, "Bob", 45000));
        employees.add(new Employee(103, "Charlie", 85000));
        employees.add(new Employee(104, "David", 55000));

        Collections.sort(employees,
                Comparator.comparing(Employee::getSalary));

        employees.forEach(System.out::println);
    }
}

🌊 Solution 2 – Java 8 Streams

import java.util.*;
import java.util.stream.Collectors;

public class SortEmployeesStream {

    public static void main(String[] args) {

        List<Employee> employees = Arrays.asList(
                new Employee(101, "Alice", 65000),
                new Employee(102, "Bob", 45000),
                new Employee(103, "Charlie", 85000),
                new Employee(104, "David", 55000)
        );

        List<Employee> sortedEmployees = employees.stream()
                .sorted(Comparator.comparing(Employee::getSalary))
                .collect(Collectors.toList());

        sortedEmployees.forEach(System.out::println);
    }
}

Explanation

Unlike primitive data types, Java cannot automatically determine how to sort custom objects such as Employee. Therefore, we must define the sorting logic using a Comparator.

In the Core Java solution, Collections.sort() sorts the list based on the comparator provided. The comparator compares employees using their salary.

In the Java 8 Stream solution, the sorted() method performs the same operation but returns a new sorted stream without modifying the original list. The Comparator.comparing() method makes the code cleaner and easier to read.

Sorting custom objects is one of the most common requirements in enterprise applications, making this an essential interview question.

Problem 4: Group Employees by Department

Difficulty Level : 🟡 Medium


Interview Question

Write a Java program to group employees by department using both Core Java and Java 8 Streams.


Problem Statement

Given a list of employees, where each employee has an ID, Name, Department, and Salary, group all employees based on their department.

This is one of the most common Java Collections interview questions because it evaluates your understanding of Map, List, Streams, and Collectors.groupingBy().


📥 Example

Input

Employee IDNameDepartmentSalary
101AliceIT65000
102BobHR45000
103CharlieIT85000
104DavidFinance55000
105EmmaHR50000

Output

IT
  Alice
  Charlie

HR
  Bob
  Emma

Finance
  David

💻 Solution 1 – Core Java

import java.util.*;

class Employee {

    private int id;
    private String name;
    private String department;
    private double salary;

    public Employee(int id, String name,
                    String department, double salary) {
        this.id = id;
        this.name = name;
        this.department = department;
        this.salary = salary;
    }

    public String getDepartment() {
        return department;
    }

    public String getName() {
        return name;
    }
}

public class GroupEmployees {

    public static void main(String[] args) {

        List<Employee> employees = Arrays.asList(

                new Employee(101,"Alice","IT",65000),
                new Employee(102,"Bob","HR",45000),
                new Employee(103,"Charlie","IT",85000),
                new Employee(104,"David","Finance",55000),
                new Employee(105,"Emma","HR",50000)
        );

        Map<String,List<Employee>> departmentMap =
                new LinkedHashMap<>();

        for(Employee employee : employees){

            departmentMap
                    .computeIfAbsent(employee.getDepartment(),
                            k -> new ArrayList<>())
                    .add(employee);
        }

        departmentMap.forEach((dept,list)->{

            System.out.println(dept);

            list.forEach(emp ->
                    System.out.println("   " + emp.getName()));
        });
    }
}

🌊 Solution 2 – Java 8 Streams

import java.util.*;
import java.util.stream.Collectors;

public class GroupEmployeesStream {

    public static void main(String[] args) {

        List<Employee> employees = Arrays.asList(

                new Employee(101,"Alice","IT",65000),
                new Employee(102,"Bob","HR",45000),
                new Employee(103,"Charlie","IT",85000),
                new Employee(104,"David","Finance",55000),
                new Employee(105,"Emma","HR",50000)
        );

        Map<String,List<Employee>> groupedEmployees =
                employees.stream()
                        .collect(Collectors.groupingBy(
                                Employee::getDepartment));

        groupedEmployees.forEach((dept,list)->{

            System.out.println(dept);

            list.forEach(emp ->
                    System.out.println("   " + emp.getName()));
        });
    }
}

Explanation

Grouping data is a common requirement in enterprise applications. Instead of processing employees one by one, organizations often need to organize them into categories such as departments, locations, or job roles.

In the Core Java solution, we create a Map<String, List<Employee>>, where the key represents the department and the value is a list of employees belonging to that department. We use computeIfAbsent() to initialize a list only when a department is encountered for the first time, making the code clean and efficient.

In the Java 8 Stream solution, the Collectors.groupingBy() method automatically groups employees based on the department returned by Employee::getDepartment. This approach is concise, expressive, and widely used in modern Java applications.

Both approaches produce the same result, but the Stream API significantly reduces boilerplate code.

Problem 5: Find the Most Frequent Element in a List

Difficulty Level : 🟡 Medium


Interview Question

Write a Java program to find the most frequent element in a List using both Core Java and Java 8 Streams.


Problem Statement

Given a list of integers, write a Java program to find the element that appears the maximum number of times in the list.

If multiple elements have the same highest frequency, return any one of them (or mention all, based on the requirement).

This question tests your understanding of List, Map, frequency counting, and Java 8 Stream operations.


📥 Example

Input

[10, 20, 10, 30, 20, 10, 40]

Output

Most Frequent Element : 10
Frequency : 3

💻 Solution 1 – Core Java

import java.util.*;

public class MostFrequentElement {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(
                10, 20, 10, 30, 20, 10, 40);

        Map<Integer, Integer> frequencyMap = new HashMap<>();

        for (Integer number : numbers) {
            frequencyMap.put(number,
                    frequencyMap.getOrDefault(number, 0) + 1);
        }

        int maxFrequency = 0;
        int mostFrequent = -1;

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

            if (entry.getValue() > maxFrequency) {
                maxFrequency = entry.getValue();
                mostFrequent = entry.getKey();
            }
        }

        System.out.println("Most Frequent Element : " + mostFrequent);
        System.out.println("Frequency : " + maxFrequency);
    }
}

Output

Most Frequent Element : 10
Frequency : 3

🌊 Solution 2 – Java 8 Streams

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostFrequentElementStream {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(
                10, 20, 10, 30, 20, 10, 40);

        Map<Integer, Long> frequencyMap = numbers.stream()
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()));

        Map.Entry<Integer, Long> result = frequencyMap.entrySet()
                .stream()
                .max(Map.Entry.comparingByValue())
                .orElse(null);

        if (result != null) {
            System.out.println("Most Frequent Element : " + result.getKey());
            System.out.println("Frequency : " + result.getValue());
        }
    }
}

Output

Most Frequent Element : 10
Frequency : 3

Explanation

Finding the most frequent element is a common interview problem that combines frequency counting with searching for the maximum value.

In the Core Java solution, we first use a HashMap to store each element and its occurrence count. After building the frequency map, we iterate through its entries to identify the element with the highest frequency.

In the Java 8 Stream solution, we again use Collectors.groupingBy() with Collectors.counting() to calculate the frequency of each element. Then, we stream over the map entries and use Map.Entry.comparingByValue() with the max() method to find the entry having the highest count.

📚 Continue Your Java Coding Interview Journey

If you found this article helpful, don't miss the previous parts of this series:

🔹 Part 1: Top 5 Java String Coding Interview Questions and Solutions (Core Java + Java 8)

👉 https://sulochanabasavala.blogspot.com/2026/07/java-string-coding-interview-questions-part-1.html

🔹 Part 2: Top 5 Java Array Coding Interview Questions and Solutions (Core Java + Java 8)

👉 https://sulochanabasavala.blogspot.com/2026/07/java-array-coding-interview-questions-part-2.html


"Stay connected for more Java, Spring Boot, React, and Full Stack Development tutorials and interview questions."

📝 Conclusion

In this article, we explored five of the most frequently asked Java Collections coding interview questions using both Core Java and Java 8 Streams. We covered essential concepts such as removing duplicate elements, counting the frequency of elements, sorting custom objects using Comparator, grouping employees by department, and finding the most frequent element in a list.

These problems helped us understand the practical usage of the Java Collections Framework, including List, Set, Map, Comparator, and the Stream API. Mastering these concepts is essential not only for Java interviews but also for building efficient and maintainable enterprise applications.

Regular practice of these coding problems will strengthen your problem-solving skills and improve your confidence in technical interviews for Java Developer, Spring Boot Developer, and Java Full Stack Developer roles.

Happy Coding! 🚀

Comments

Popular posts from this blog

React Basics – How to Create Component

How to Build REST API using Spring Boot (Step-by-Step Guide)

Spring Boot @RequestParam Annotation Explained with Real-Time Examples