Java Collection Framework Coding Problems with Solutions


The Java Collection Framework provides a set of interfaces and classes to store and manipulate groups of data as a single unit. In this article, we will discuss some common coding problems related to the Java Collection Framework and provide solutions to these problems.


java collection interface - to represent and manipulate collections in java


Given a list of integers, write a Java program to remove all duplicate elements from the list.


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RemoveDuplicates {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(4);
        list.add(5);

        Set<Integer> set = new HashSet<>(list);
        list.clear();
        list.addAll(set);

        System.out.println("List after removing duplicates: " + list);
    }
}

Solution: In the above code, we use a HashSet to remove duplicates because sets do not allow duplicate elements. We then clear the original list and add all elements from the set back to the list.

remove duplicates from the list


Write a Java program to find the frequency of each element in a given list.


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FrequencyCounter {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("banana");
        list.add("apple");
        list.add("orange");
        list.add("banana");
        list.add("apple");

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

        for (String item : list) {
            frequencyMap.put(item, frequencyMap.getOrDefault(item, 0) + 1);
        }

        System.out.println("Frequency of elements: " + frequencyMap);
    }
}

Solution: This code uses a HashMap to count the frequency of each element in the list. The getOrDefault method is used to handle the case where an element is not already present in the map.


frequency of elements - using hashmap in java



Given a list of custom objects (e.g., a list of employees with names and ages), write a Java program to sort the list by age.


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee {
    String name;
    int age;

    Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

public class SortEmployees {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee("Alice", 30));
        employees.add(new Employee("Bob", 25));
        employees.add(new Employee("Charlie", 35));

        Collections.sort(employees, new Comparator<Employee>() {
            @Override
            public int compare(Employee e1, Employee e2) {
                return Integer.compare(e1.age, e2.age);
            }
        });

        System.out.println("Sorted list of employees: " + employees);
    }
}

Solution: In this example, we define a custom Employee class with name and age attributes. We then use the Collections.sort method along with a custom Comparator to sort the list of employees by age.



Given a list of strings, write a Java program to sort the list by the length of the strings in ascending order.


1. Using Compartor


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortByLength {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("apple");
        list.add("banana");
        list.add("kiwi");
        list.add("pear");
        list.add("pineapple");

        Collections.sort(list, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return Integer.compare(s1.length(), s2.length());
            }
        });

        System.out.println("List sorted by length: " + list);
    }
}

Solution: In the above code, we use the Collections.sort method with a custom Comparator to sort the list of strings by their lengths.


2. Using Comparable



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

class StringWithLength implements Comparable {
    private String value;

    public StringWithLength(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public int compareTo(StringWithLength other) {
        return Integer.compare(this.value.length(), other.value.length());
    }

    @Override
    public String toString() {
        return value;
    }
}

public class SortStringsByLength {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add(new StringWithLength("apple"));
        list.add(new StringWithLength("banana"));
        list.add(new StringWithLength("kiwi"));
        list.add(new StringWithLength("pear"));
        list.add(new StringWithLength("pineapple"));

        Collections.sort(list);

        System.out.println("List sorted by length: " + list);
    }
}



Solution: In this solution, we use the compareTo method in a custom class to define how the strings should be compared based on their lengths. This demonstrates how to implement sorting using compareTo for a specific comparison logic..




By solving these common coding problems, you can better understand and utilize the Java Collection Framework in your applications. For more advanced topics and examples, explore the Java documentation and other resources available online.







Read Next