Java Collection Framework Examples with Explanation

Java Collection Framework Examples with Explanation

Here are key Java Collection Framework topics frequently discussed in interviews, along with explanations and example code:


1. Difference Between List, Set, and Map

Understanding the differences between these core interfaces is crucial in interviews.

Explanation:

  1. List: Allows duplicate elements and maintains insertion order.
    • Implementations: ArrayList, LinkedList, Vector.
  2. Set: Does not allow duplicate elements and does not guarantee order.
    • Implementations: HashSet, LinkedHashSet, TreeSet.
  3. Map: Stores key-value pairs. Keys are unique, but values can duplicate.
    • Implementations: HashMap, TreeMap, LinkedHashMap.

2. HashMap Internal Working

One of the most frequently asked questions in interviews.

Explanation:

  • HashMap uses a combination of an array and a linked list (or tree since Java 8).
  • Key Features:
    • Keys are hashed using hashCode().
    • The hash determines the index of the bucket in the array.
    • Collision resolution uses chaining (linked list or tree).

Example:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("One", 1);
        map.put("Two", 2);
        map.put("Three", 3);

        System.out.println("Value for 'Two': " + map.get("Two"));
    }
}

Interview Tip: Be ready to discuss rehashing, load factors, and how collisions are resolved in detail.


3. Difference Between ArrayList and LinkedList

This is a common comparison asked in interviews.

Key Differences:

Feature ArrayList LinkedList
Storage Dynamic array Doubly linked list
Access Time O(1) for random access O(n) for random access
Insertion/Deletion Slow (O(n)) Fast (O(1)) if at the ends
Memory Less memory overhead More memory overhead

Example:

import java.util.*;

public class ListExample {
    public static void main(String[] args) {
        List<Integer> arrayList = new ArrayList<>();
        List<Integer> linkedList = new LinkedList<>();

        arrayList.add(1);
        linkedList.add(1);

        System.out.println("ArrayList: " + arrayList);
        System.out.println("LinkedList: " + linkedList);
    }
}

4. ConcurrentHashMap vs HashMap

Key Differences:

Feature HashMap ConcurrentHashMap
Thread Safety Not thread-safe Thread-safe
Null Key/Values Allows 1 null key, multiple null values Does not allow null keys or values
Performance Faster in single-threaded environments Optimized for concurrent access

Example:

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
        map.put("One", 1);
        map.put("Two", 2);

        System.out.println("Value for 'One': " + map.get("One"));
    }
}

Interview Tip: Be prepared to explain segment locking and how it improves performance in ConcurrentHashMap.


5. Sorting Using Collections Framework

Sorting is a frequently tested topic.

Example: Sorting a List

import java.util.*;

public class SortingExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(4, 2, 5, 1, 3);
        Collections.sort(numbers);
        System.out.println("Sorted List: " + numbers);

        // Custom sorting (Descending)
        numbers.sort((a, b) -> b - a);
        System.out.println("Custom Sorted List: " + numbers);
    }
}

Example: Sorting with Comparator

import java.util.*;

class Student {
    String name;
    int marks;

    public Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

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

public class ComparatorExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 85));
        students.add(new Student("Bob", 95));
        students.add(new Student("Charlie", 75));

        // Sort by marks
        students.sort((s1, s2) -> s2.marks - s1.marks);
        System.out.println("Sorted by Marks: " + students);
    }
}

6. TreeMap vs HashMap

Key Differences:

Feature HashMap TreeMap
Ordering No ordering guarantee Keys are sorted
Performance O(1) for basic operations O(log n) for basic operations
Null Key Allows one null key Does not allow null keys

Example:

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        TreeMap<String, Integer> treeMap = new TreeMap<>();
        treeMap.put("Apple", 3);
        treeMap.put("Banana", 2);
        treeMap.put("Cherry", 5);

        System.out.println("TreeMap: " + treeMap);
    }
}

7. How to Remove Duplicates From a List

This is a popular coding question.

Example:

import java.util.*;

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

        Set<Integer> uniqueSet = new HashSet<>(list);
        List<Integer> uniqueList = new ArrayList<>(uniqueSet);

        System.out.println("Original List: " + list);
        System.out.println("List without Duplicates: " + uniqueList);
    }
}

Interview Tip: You can also use Stream APIs to achieve this.


8. Implementing a Custom LinkedList

Understanding the internal workings of LinkedList is vital.

Example:

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class CustomLinkedList {
    Node head;

    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = newNode;
        }
    }

    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + " -> ");
            temp = temp.next;
        }
        System.out.println("null");
    }
}

public class CustomLinkedListExample {
    public static void main(String[] args) {
        CustomLinkedList list = new CustomLinkedList();
        list.add(1);
        list.add(2);
        list.add(3);

        list.printList();
    }
}

Key Interview Tips for Collections Framework:

  1. Understand Internal Workings: Know-how HashMap, HashSet, ArrayList, etc., work internally.
  2. Big-O Complexity: Be ready to discuss the time and space complexities.
  3. Thread Safety: Know the thread-safe alternatives like ConcurrentHashMap, CopyOnWriteArrayList.
  4. Use Cases: Understand which collection to use in specific scenarios.
  5. Custom Implementations: Be prepared to write custom implementations like  LinkedList or a HashMap.

Let me know if you need further assistance! 😊

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