Java Collection Framework examples with Explanation

Java Collection Framework Examples with Explanation

Here are practical Java Collection Framework examples tailored for interviews, complete with explanations:


1. Iterate Over a Map

Interviewers often ask about efficient ways to iterate over a Map.

Example:

import java.util.*;

public class IterateMapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Alice", 25);
        map.put("Bob", 30);
        map.put("Charlie", 35);

        // Iterating using EntrySet
        System.out.println("Using EntrySet:");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        // Iterating using forEach (Java 8+)
        System.out.println("\nUsing forEach:");
        map.forEach((key, value) -> System.out.println(key + " -> " + value));
    }
}

Explanation:

  • entrySet(): Retrieves a set of key-value pairs for iteration.
  • forEach: A concise method introduced in Java 8 for iterating with lambda expressions.

2. Remove Elements While Iterating

This tests your understanding of fail-fast behavior and how to avoid ConcurrentModificationException.

Example:

import java.util.*;

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

        // Correct way using Iterator
        Iterator<Integer> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() % 2 == 0) {
                iterator.remove(); // Safe removal
            }
        }

        System.out.println("Modified List: " + list);
    }
}

Explanation:

  • Fail-fast behaviour: Directly modifying the collection during iteration without using an iterator causes ConcurrentModificationException.
  • iterator.remove(): Safely removes the current element.

3. Compare Two Lists

A common interview question is to compare two lists for equality, intersection, or difference.

Example:

import java.util.*;

public class CompareLists {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("A", "B", "C");
        List<String> list2 = Arrays.asList("B", "C", "D");

        // Find common elements
        List<String> intersection = new ArrayList<>(list1);
        intersection.retainAll(list2);
        System.out.println("Intersection: " + intersection);

        // Find difference
        List<String> difference = new ArrayList<>(list1);
        difference.removeAll(list2);
        System.out.println("Difference: " + difference);

        // Check equality
        boolean areEqual = list1.equals(list2);
        System.out.println("Are lists equal? " + areEqual);
    }
}

Explanation:

  • retainAll(): Keeps only common elements.
  • removeAll(): Removes elements present in another collection.
  • equals(): Compares the lists for order and content equality.

4. Convert List to Map

This demonstrates creating a Map from a List.

Example:

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

public class ListToMap {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

        // Convert List to Map using Streams
        Map<String, Integer> nameLengthMap = names.stream()
            .collect(Collectors.toMap(name -> name, name -> name.length()));

        System.out.println("Map: " + nameLengthMap);
    }
}

Explanation:

  • toMap: Collects stream elements into a map.
  • name -> name.length(): Uses the name as the key and its length as the value.

5. Find the First Non-Repeated Character

This tests your ability to use Map character frequency counting.

Example:

import java.util.*;

public class FirstNonRepeatedChar {
    public static void main(String[] args) {
        String input = "swiss";
        Map<Character, Integer> frequencyMap = new LinkedHashMap<>();

        for (char c : input.toCharArray()) {
            frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
        }

        for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
            if (entry.getValue() == 1) {
                System.out.println("First non-repeated character: " + entry.getKey());
                break;
            }
        }
    }
}

Explanation:

  • LinkedHashMap: Maintains insertion order.
  • getOrDefault: Gets the value or returns a default if the key is absent.

6. Implement a Stack Using Deque

A common question is to implement a Stack using a Deque.

Example:

import java.util.*;

public class StackUsingDeque {
    public static void main(String[] args) {
        Deque<Integer> stack = new ArrayDeque<>();

        // Push elements
        stack.push(10);
        stack.push(20);
        stack.push(30);

        // Pop elements
        System.out.println("Popped: " + stack.pop());
        System.out.println("Stack after pop: " + stack);
    }
}

Explanation:

  • Deque provides push, pop, and peek methods, making it ideal for implementing a stack.
  • ArrayDeque Is faster than Stack.

7. Thread-Safe Collections

Understand and use thread-safe alternatives.

Example:

import java.util.*;
import java.util.concurrent.*;

public class ThreadSafeCollections {
    public static void main(String[] args) {
        List<Integer> synchronizedList = Collections.synchronizedList(new ArrayList<>());

        synchronizedList.add(1);
        synchronizedList.add(2);

        synchronized (synchronizedList) {
            for (int num : synchronizedList) {
                System.out.println(num);
            }
        }

        // Concurrent Collection
        CopyOnWriteArrayList<Integer> concurrentList = new CopyOnWriteArrayList<>();
        concurrentList.add(3);
        concurrentList.add(4);

        for (int num : concurrentList) {
            System.out.println(num);
        }
    }
}

Explanation:

  • Collections.synchronizedList: Wraps a collection to make it thread-safe.
  • CopyOnWriteArrayList: A concurrent list for safe iteration without external synchronization.

8. Implementing a Priority Queue

This demonstrates how to use a PriorityQueue for custom sorting.

Example:

import java.util.*;

public class CustomPriorityQueue {
    public static void main(String[] args) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

        minHeap.add(5);
        minHeap.add(1);
        minHeap.add(3);

        maxHeap.add(5);
        maxHeap.add(1);
        maxHeap.add(3);

        System.out.println("Min-Heap: " + minHeap);
        System.out.println("Max-Heap: " + maxHeap);
    }
}

Explanation:

  • PriorityQueue: By default, implements a min-heap.
  • Collections.reverseOrder: Converts it to a max-heap.

9. Frequency of Words in a String

This demonstrates using Map for counting word frequencies.

Example:

import java.util.*;

public class WordFrequency {
    public static void main(String[] args) {
        String input = "Java Collection Framework is powerful powerful";
        Map<String, Integer> frequencyMap = new HashMap<>();

        for (String word : input.split(" ")) {
            frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1);
        }

        System.out.println("Word Frequencies: " + frequencyMap);
    }
}

Explanation:

  • split(" "): Splits the string into words.
  • frequencyMap.put(word, frequencyMap.getOrDefault(word, 0) + 1): Updates the count for each word.

Interview Tips:

  1. Understand Internal Mechanics: Be ready to explain how collections like HashMap or ArrayList work internally.
  2. Time Complexity: Know the complexities of common operations (add, remove, get).
  3. Thread-Safe Collections: Understand the differences between synchronized and concurrent collections.
  4. Coding Questions: Practice solving problems like duplicate removal, intersection, and custom sorting using collections.

Let me know if you’d like more examples or deeper explanations! 😊

Prakash Bojja

I have a personality with all the positives, which makes me a dynamic personality with charm. I am a software professional with capabilities far beyond those of anyone who claims to be excellent.

Post a Comment

Previous Post Next Post

Contact Form