Advanced Java programs using Collections Framework with explanations

Advanced Java Programs using Collections Framework with explanations,

Here are examples of advanced Java programs using Collections Framework with explanations:


1. Sorting a List with a Comparator

This program demonstrates sorting a list of objects using a custom 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 CustomSort {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 85));
        students.add(new Student("Bob", 75));
        students.add(new Student("Charlie", 95));

        // Sort by marks
        students.sort((s1, s2) -> s2.marks - s1.marks);

        System.out.println("Sorted by Marks (Descending):");
        students.forEach(System.out::println);
    }
}

Explanation:

  • students.sort((s1, s2) -> s2.marks - s1.marks);: Uses a lambda expression to sort students by marks in descending order.
  • List<Student>: Demonstrates how generics work in collections.

2. Using HashMap to Count Word Frequencies

This program counts the frequency of words in a string using a HashMap.

import java.util.*;

public class WordFrequency {
    public static void main(String[] args) {
        String text = "Java collections are powerful and flexible powerful";

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

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

        System.out.println("Word Frequencies:");
        wordCount.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Explanation:

  • getOrDefault(word, 0): Retrieves the current count or defaults to 0 if the word is not yet in the map.
  • wordCount.put(word, count + 1): Updates the frequency of the word.

3. LinkedHashMap for LRU Cache

This program implements an LRU (Least Recently Used) cache using. LinkedHashMap.

import java.util.*;

class LRUCache<K, V> extends LinkedHashMap<K, V> {
    private final int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }
}

public class LRUCacheExample {
    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: " + cache);

        cache.get(2); // Access key 2
        cache.put(4, "D"); // Add a new entry, 1 will be evicted
        System.out.println("Cache after accessing 2 and adding 4: " + cache);
    }
}

Explanation:

  • removeEldestEntry: Ensures the size of the cache does not exceed the capacity.
  • LinkedHashMap Maintains the insertion order or access order when it true is passed to the constructor.

4. Using PriorityQueue for Task Scheduling

This program uses a PriorityQueue to manage tasks based on their priority.

import java.util.*;

class Task implements Comparable<Task> {
    String name;
    int priority;

    public Task(String name, int priority) {
        this.name = name;
        this.priority = priority;
    }

    @Override
    public int compareTo(Task other) {
        return Integer.compare(this.priority, other.priority);
    }

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

public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<Task> taskQueue = new PriorityQueue<>();

        taskQueue.add(new Task("Task A", 3));
        taskQueue.add(new Task("Task B", 1));
        taskQueue.add(new Task("Task C", 2));

        while (!taskQueue.isEmpty()) {
            System.out.println("Processing: " + taskQueue.poll());
        }
    }
}

Explanation:

  • PriorityQueue<Task>: Orders tasks based on their priority (lowest first).
  • compareTo: Defines natural ordering for Task.

5. TreeMap for Sorted Key-Value Storage

This program demonstrates the use of TreeMap to store and retrieve sorted key-value pairs.

import java.util.*;

public class TreeMapExample {
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>();

        map.put(3, "Three");
        map.put(1, "One");
        map.put(2, "Two");

        System.out.println("Sorted Map:");
        map.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Explanation:

  • TreeMap Automatically sorts entries by keys.
  • Useful for scenarios where sorted data is required.

6. Grouping Using Streams API

This program demonstrates grouping elements using the Streams API and Collectors.groupingBy.

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

class Employee {
    String department;
    String name;

    public Employee(String department, String name) {
        this.department = department;
        this.name = name;
    }

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

public class GroupingExample {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("HR", "Alice"),
            new Employee("IT", "Bob"),
            new Employee("HR", "Charlie"),
            new Employee("IT", "Diana"),
            new Employee("Finance", "Eve")
        );

        Map<String, List<Employee>> grouped = employees.stream()
            .collect(Collectors.groupingBy(emp -> emp.department));

        System.out.println("Employees Grouped by Department:");
        grouped.forEach((dept, emps) -> System.out.println(dept + ": " + emps));
    }
}

Explanation:

  • Collectors.groupingBy: Groups employees by department.
  • The result is a Map with the department as the key and a list of employees as the value.

7. ConcurrentHashMap for Thread-Safe Operations

This program demonstrates thread-safe map operations using. ConcurrentHashMap.

import java.util.concurrent.*;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        // Adding elements
        map.put("A", 1);
        map.put("B", 2);

        // Updating elements safely
        map.computeIfPresent("A", (key, val) -> val + 1);

        // Retrieving elements
        map.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Explanation:

  • computeIfPresent: Updates a value atomically if the key exists.
  • ConcurrentHashMap: Provides thread-safe operations without locking the entire map.

These programs cover advanced use cases of Java's Collections Framework, including custom sorting, frequency counting, caching, priority-based processing, grouping, and thread-safe operations. Let me know if you want more examples! 😊

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