Today you will learn:
<T>) for classes, methods, and collectionsTreeSet, TreeMap, PriorityQueueCollections.sort and Collections.reverseBy the end, you will be able to write type-safe code and use advanced collection features effectively.
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
Advanced collections include sorted sets and maps, and queues with priority.
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
import java.util.TreeMap;
TreeMap scores = new TreeMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
System.out.println(scores); // sorted by keys
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
}
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]
Common methods:
Collections.sort(list) – sorts ascendingCollections.reverse(list) – reverses orderCollections.shuffle(list) – randomizes order
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);
Create a PriorityQueue of integers and remove elements in ascending order.
Steps:
PriorityQueue<Integer>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
}
}