Advanced Java Day 1: Generics and Advanced Collections

Goal of this Day

Today you will learn:

By the end, you will be able to write type-safe code and use advanced collection features effectively.

Step 1: Generics Basics

Generics allow you to define classes or methods with a type parameter <T>.


public class Box<T> {
    private T content;

    public void setContent(T content) {
        this.content = content;
    }

    public T getContent() {
        return content;
    }
}

Box<String> box = new Box<>();
box.setContent("Hello");
System.out.println(box.getContent()); // Hello

Step 2: Collections Deep Dive

Advanced collections include sorted sets and maps, and queues with priority.

TreeSet


import java.util.TreeSet;

TreeSet set = new TreeSet<>();
set.add(5);
set.add(3);
set.add(8);

System.out.println(set); // [3, 5, 8] automatically sorted

TreeMap


import java.util.TreeMap;

TreeMap scores = new TreeMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);

System.out.println(scores); // sorted by keys

PriorityQueue


import java.util.PriorityQueue;

PriorityQueue pq = new PriorityQueue<>();
pq.add(10);
pq.add(5);
pq.add(15);

while(!pq.isEmpty()) {
    System.out.println(pq.poll()); // 5, 10, 15
}

Step 3: Custom Comparators

You can sort collections using custom logic.


import java.util.*;

List names = Arrays.asList("Alice", "Bob", "Charlie");

Collections.sort(names, (a, b) -> b.compareTo(a)); // descending order
System.out.println(names); // [Charlie, Bob, Alice]

Step 4: Collections Utilities

Common methods:

Practice


import java.util.*;

List<String> names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie"));
Collections.sort(names);
System.out.println(names);

Map<String, Integer> scores = new TreeMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
System.out.println(scores);

Exercise

Create a PriorityQueue of integers and remove elements in ascending order.

Steps:

Example:


import java.util.PriorityQueue;

public class PriorityQueueExample {
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(10);
        pq.add(5);
        pq.add(20);
        pq.add(1);

        while(!pq.isEmpty()) {
            System.out.println(pq.poll());
        }
        // Output: 1, 5, 10, 20
    }
}