Challenging Java Collections Framework Coding Problems for Success

Java Collections Framework Coding Problems

Here are a few Interview Java Collections Framework coding problems. These Java Collections framework coding problems test your understanding of different collection classes and their utilize cases in practical scenarios.By understanding these Java Collections Framework coding problems, you’ll sharpen your skills in managing information proficiently and acing common tasks like searching, sorting, and iteration in Java.

Java Collections Framework Coding Problems
Java Collections Framework Coding Problems

1.Reverse a List using List in Java

import java.util.*;

public class ReverseList {

public static void main(String[] args) {

List list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5));

// Your code here to reverse the list

Collections.reverse(list);

System.out.println(“Reversed List:” + list);

}

}

Output:

Reversed List: [5, 4, 3, 2, 1]

2.Check for Duplicates in a list using HashSet

import java.util.*;

public class CheckDuplicates {

public static boolean containsDuplicates(List<Integer> list) {

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

return set.size() != list.size(); // If set size is different, duplicates exist

}

public static void main(String[] args) {

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 1);

System.out.println(“Contains duplicates: ” + containsDuplicates(list)); // true

}

}

Output:

Contains duplicates: true

3.Find the Intersection of Two Lists

import java.util.*;

public class IntersectionOfLists {

public static List<Integer> findIntersection(List<Integer> list1, List<Integer> list2) {

Set<Integer> set1 = new HashSet<>(list1);

Set<Integer> set2 = new HashSet<>(list2);

set1.retainAll(set2); // Retain only elements that are in both sets

return new ArrayList<>(set1);

}

public static void main(String[] args) {

List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> list2 = Arrays.asList(4, 5, 6, 7, 8);

List<Integer> intersection = findIntersection(list1, list2);

System.out.println(“Intersection: ” + intersection); // [4, 5]

}

}

Output:

Intersection: [4, 5]

4.Find the Union of Two Lists

import java.util.*;

public class UnionOfLists {

public static List<Integer> findUnion(List<Integer> list1, List<Integer> list2) {

Set<Integer> set = new HashSet<>(list1);

set.addAll(list2); // Add all elements from list2, duplicates will be avoided

return new ArrayList<>(set);

}

public static void main(String[] args) {

List<Integer> list1 = Arrays.asList(1, 2, 3, 4);

List<Integer> list2 = Arrays.asList(3, 4, 5, 6);

List<Integer> union = findUnion(list1, list2);

System.out.println(“Union: ” + union); // [1, 2, 3, 4, 5, 6]

}

}

Output:

Union: [1, 2, 3, 4, 5, 6]

5.Implement an LRU Cache using LinkedHashMap

import java.util.*;

public class LRUCache<K, V> {

private final int capacity;

private final LinkedHashMap<K, V> map;

public LRUCache(int capacity) {

this.capacity = capacity;

this.map = new LinkedHashMap<>(capacity, 0.75f, true);

}

public V get(K key) {

return map.getOrDefault(key, null);

}

public void put(K key, V value) {

if (map.size() >= capacity) {

Iterator<Map.Entry<K, V>> iterator = map.entrySet().iterator();

iterator.next(); // Remove the least recently used entry

iterator.remove();

}

map.put(key, value);

}

public static void main(String[] args) {

LRUCache<Integer, String> cache = new LRUCache<>(3);

cache.put(1, “A”);

cache.put(2, “B”);

cache.put(3, “C”);

System.out.println(cache.get(1)); // A

cache.put(4, “D”);

System.out.println(cache.get(2)); // null, because 2 was evicted

System.out.println(cache.get(1)); // A

System.out.println(cache.get(4)); // D

}

}

Output:

A

null

A

D

6.Sort a List of Objects using Comparator

import java.util.*;

class Person {

String name;

int age;

Person(String name, int age) {

this.name = name;

this.age = age;

}

@Override

public String toString() {

return name + ” (” + age + “)”;

}

}

public class SortObjects {

public static void main(String[] args) {

List<Person> people = Arrays.asList(

new Person(“Alice”, 30),

new Person(“Bob”, 25),

new Person(“Charlie”, 35)

);

// Sort by age

people.sort(Comparator.comparingInt(p -> p.age));

System.out.println(people); // [Bob (25), Alice (30), Charlie (35)]

}

}

Output:

[Bob (25), Alice (30), Charlie (35)]

7.Remove All Occurrences of a Specific Element

import java.util.*;

public class RemoveOccurrences {

public static void removeElement(List<Integer> list, Integer element) {

list.removeIf(e -> e.equals(element));

}

public static void main(String[] args) {

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 3, 5, 3));

removeElement(list, 3);

System.out.println(“Updated List: ” + list); // [1, 2, 4, 5]

}

}

Output:

Updated List: [1, 2, 4, 5]

8.Merge Two Sorted Lists into one Sorted List

import java.util.*;

public class MergeSortedLists {

public static List<Integer> mergeSortedLists(List<Integer> list1, List<Integer> list2) {

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

int i = 0, j = 0;

while (i < list1.size() && j < list2.size()) {

if (list1.get(i) < list2.get(j)) {

mergedList.add(list1.get(i++));

} else {

mergedList.add(list2.get(j++));

}

}

// Add remaining elements

mergedList.addAll(list1.subList(i, list1.size()));

mergedList.addAll(list2.subList(j, list2.size()));

return mergedList;

}

public static void main(String[] args) {

List<Integer> list1 = Arrays.asList(1, 3, 5, 7);

List<Integer> list2 = Arrays.asList(2, 4, 6, 8);

List<Integer> merged = mergeSortedLists(list1, list2);

System.out.println(“Merged List: ” + merged); // [1, 2, 3, 4, 5, 6, 7, 8]

}

}

output:

Merged List: [1, 2, 3, 4, 5, 6, 7, 8]

9.Implement contains() for a List using Iterator

import java.util.*;

public class ListContains {

public static boolean contains(List<Integer> list, Integer element) {

Iterator<Integer> iterator = list.iterator();

while (iterator.hasNext()) {

if (iterator.next().equals(element)) {

return true;

}

}

return false;

}

public static void main(String[] args) {

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

System.out.println(contains(list, 3)); // true

System.out.println(contains(list, 6)); // false

}

}

Output:

true

false

10.Find the Frequency of Elements in a List using Map

import java.util.*;

public class FrequencyCounter {

public static Map<Integer, Integer> countFrequency(List<Integer> list) {

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

for (Integer num : list) {

frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);

}

return frequencyMap;

}

public static void main(String[] args) {

List<Integer> list = Arrays.asList(1, 2, 3, 1, 2, 1, 4, 5, 2, 1);

Map<Integer, Integer> frequencyMap = countFrequency(list);

// Print the frequency of each element

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

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

}

}

}

Output:

1: 4

2: 3

3: 1

4: 1

5: 1

11.Group Words by Anagram  using Map

import java.util.*;

public class GroupAnagrams {

public static List<List<String>> groupAnagrams(List<String> words) {

Map<String, List<String>> anagramMap = new HashMap<>();

for (String word : words) {

// Sort the word and use it as a key

char[] chars = word.toCharArray();

Arrays.sort(chars);

String sortedWord = new String(chars);

// If the sorted word is not in the map, add it with a new list

anagramMap.computeIfAbsent(sortedWord, k -> new ArrayList<>()).add(word);

}

// Return the values of the map as a list of lists

return new ArrayList<>(anagramMap.values());

}

public static void main(String[] args) {

List words = Arrays.asList(“eat”, “tea”, “tan”, “ate”, “nat”, “bat”);

List groupedAnagrams = groupAnagrams(words);

// Print the groups of anagrams

System.out.println(groupedAnagrams);

}

}

Input:

List<String> words = Arrays.asList("eat", "tea", "tan", "ate", "nat", "bat");

Output:

[["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]

Leave a Comment