Utilities
Collections Utility Class
When working with Lists, Sets, and other collections, you frequently need to sort, shuffle, or find extreme values. The Collections utility class provides static methods for these operations, plus ways to create thread-safe and unmodifiable collection views.
Sorting Collections
Sort lists using natural ordering or custom comparators.
Sort.java
// Collections.sort examples
import java.util.*;
public class Sort {
public static void main(String[] args) {
System.out.println("Sort list:");
List<Integer> nums = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9, 3));
System.out.println("Original: " + nums);
Collections.sort(nums);
System.out.println("Sorted: " + nums);
System.out.println("\nSort strings:");
List<String> fruits = new ArrayList<>(Arrays.asList("banana", "apple", "cherry", "date"));
System.out.println("Original: " + fruits);
Collections.sort(fruits);
System.out.println("Sorted: " + fruits);
System.out.println("\nSort with comparator:");
List<String> words = new ArrayList<>(Arrays.asList("cat", "elephant", "dog", "butterfly"));
System.out.println("Original: " + words);
Collections.sort(words, (a, b) -> a.length() - b.length());
System.out.println("By length: " + words);
System.out.println("\nReverse order:");
List<Integer> values = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("Original: " + values);
Collections.sort(values, Collections.reverseOrder());
System.out.println("Reversed: " + values);
System.out.println("\nCase-insensitive sort:");
List<String> names = new ArrayList<>(Arrays.asList("alice", "Bob", "CHARLIE", "david"));
System.out.println("Original: " + names);
Collections.sort(names, String.CASE_INSENSITIVE_ORDER);
System.out.println("Sorted: " + names);
System.out.println("\nSort custom objects:");
List<Student> students = new ArrayList<>(Arrays.asList(
new Student("Alice", 85),
new Student("Bob", 92),
new Student("Charlie", 78),
new Student("David", 95)
));
System.out.println("Original:");
students.forEach(System.out::println);
Collections.sort(students, (a, b) -> Integer.compare(a.grade, b.grade));
System.out.println("\nSorted by grade:");
students.forEach(System.out::println);
System.out.println("\nStable sort:");
List<Student> students2 = new ArrayList<>(Arrays.asList(
new Student("Alice", 85),
new Student("Bob", 85),
new Student("Charlie", 92),
new Student("David", 85)
));
System.out.println("Original:");
students2.forEach(System.out::println);
Collections.sort(students2, (a, b) -> Integer.compare(a.grade, b.grade));
System.out.println("\nSorted (stable):");
students2.forEach(System.out::println);
System.out.println("\nMultiple sort criteria:");
List<Student> students3 = new ArrayList<>(Arrays.asList(
new Student("Alice", 85),
new Student("Bob", 92),
new Student("Charlie", 85),
new Student("David", 92)
));
Comparator<Student> byGradeThenName =
Comparator.comparing((Student s) -> s.grade)
.thenComparing(s -> s.name);
Collections.sort(students3, byGradeThenName);
System.out.println("Sorted by grade, then name:");
students3.forEach(System.out::println);
}
static class Student {
String name;
int grade;
Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
@Override
public String toString() {
return String.format(" %s: %d", name, grade);
}
}
}
Collections class
A utility class in java.util providing static methods for collection manipulation, distinct from the Collection interface.
Natural ordering
The default sort order defined by the element's Comparable implementation, like alphabetical for strings.
Reversing Collections
Reverse the order of elements in a list.
Reverse.java
// Collections.reverse and rotate examples
import java.util.*;
public class Reverse {
public static void main(String[] args) {
System.out.println("Reverse list:");
List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("Original: " + nums);
Collections.reverse(nums);
System.out.println("Reversed: " + nums);
System.out.println("\nReverse strings:");
List<String> words = new ArrayList<>(Arrays.asList("first", "second", "third", "fourth"));
System.out.println("Original: " + words);
Collections.reverse(words);
System.out.println("Reversed: " + words);
System.out.println("\nReverse twice:");
List<Integer> values = new ArrayList<>(Arrays.asList(10, 20, 30, 40));
System.out.println("Original: " + values);
Collections.reverse(values);
System.out.println("Reversed: " + values);
Collections.reverse(values);
System.out.println("Reversed again: " + values);
System.out.println("\nRotate list:");
List<Integer> rotate = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("Original: " + rotate);
Collections.rotate(rotate, 2);
System.out.println("Rotate +2: " + rotate);
Collections.rotate(rotate, -2);
System.out.println("Rotate -2: " + rotate);
System.out.println("\nRotate examples:");
List<String> days = new ArrayList<>(Arrays.asList("Mon", "Tue", "Wed", "Thu", "Fri"));
System.out.println("Days: " + days);
Collections.rotate(days, 1);
System.out.println("Rotate 1: " + days);
Collections.rotate(days, -3);
System.out.println("Rotate -3: " + days);
System.out.println("\nSwap elements:");
List<Integer> list = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
System.out.println("Original: " + list);
Collections.swap(list, 0, 4);
System.out.println("Swap 0,4: " + list);
Collections.swap(list, 1, 3);
System.out.println("Swap 1,3: " + list);
System.out.println("\nPalindrome check:");
List<Integer> pal1 = new ArrayList<>(Arrays.asList(1, 2, 3, 2, 1));
List<Integer> pal2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("List 1: " + pal1);
System.out.println("Palindrome? " + isPalindrome(pal1));
System.out.println("List 2: " + pal2);
System.out.println("Palindrome? " + isPalindrome(pal2));
System.out.println("\nCycle through list:");
List<String> queue = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
System.out.println("Queue: " + queue);
for (int i = 0; i < 3; i++) {
String first = queue.remove(0);
queue.add(first);
System.out.println("Cycle: " + queue);
}
System.out.println("\nReverse sublist:");
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
System.out.println("Original: " + numbers);
List<Integer> sublist = numbers.subList(2, 6);
Collections.reverse(sublist);
System.out.println("Reverse [2,6): " + numbers);
}
static <T> boolean isPalindrome(List<T> list) {
List<T> reversed = new ArrayList<>(list);
Collections.reverse(reversed);
return list.equals(reversed);
}
}
Shuffling Collections
Randomly reorder elements for games, sampling, or testing.
Shuffle.java
// Collections.shuffle and fill examples
import java.util.*;
public class Shuffle {
public static void main(String[] args) {
int seed = ;
System.out.println("Shuffle list:");
List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
System.out.println("Original: " + nums);
Collections.shuffle(nums, new Random(seed));
System.out.println("Shuffled: " + nums);
System.out.println("\nShuffle with seed:");
List<Integer> nums1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> nums2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Random rand = new Random(seed);
Collections.shuffle(nums1, rand);
rand = new Random(seed);
Collections.shuffle(nums2, rand);
System.out.println("Shuffle 1: " + nums1);
System.out.println("Shuffle 2: " + nums2);
System.out.println("Same? " + nums1.equals(nums2));
System.out.println("\nShuffle deck:");
List<String> deck = new ArrayList<>();
String[] suits = {"♠", "♥", "♦", "♣"};
String[] ranks = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
for (String suit : suits) {
for (String rank : ranks) {
deck.add(rank + suit);
}
}
System.out.println("Deck size: " + deck.size());
System.out.println("First 13: " + deck.subList(0, 13));
Collections.shuffle(deck, new Random(seed + 1));
System.out.println("After shuffle: " + deck.subList(0, 13));
System.out.println("\nDeal cards:");
Collections.shuffle(deck, new Random(seed + 2));
for (int player = 0; player < 4; player++) {
List<String> hand = deck.subList(player * 5, (player + 1) * 5);
System.out.println("Player " + (player + 1) + ": " + hand);
}
System.out.println("\nFill list:");
List<Integer> values = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("Original: " + values);
Collections.fill(values, 0);
System.out.println("Filled with 0: " + values);
System.out.println("\nFill strings:");
List<String> words = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
System.out.println("Original: " + words);
Collections.fill(words, "X");
System.out.println("Filled: " + words);
System.out.println("\nInitialize with fill:");
List<Boolean> flags = new ArrayList<>(10);
for (int i = 0; i < 10; i++) flags.add(null);
Collections.fill(flags, true);
System.out.println("Flags: " + flags);
System.out.println("\nRandom sample:");
List<Integer> population = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
population.add(i);
}
Collections.shuffle(population, new Random(seed + 3));
List<Integer> sample = population.subList(0, 10);
Collections.sort(sample);
System.out.println("Random sample of 10: " + sample);
System.out.println("\nLottery numbers:");
List<Integer> lottery = new ArrayList<>();
for (int i = 1; i <= 49; i++) {
lottery.add(i);
}
Collections.shuffle(lottery, new Random(seed + 4));
List<Integer> picked = new ArrayList<>(lottery.subList(0, 6));
Collections.sort(picked);
System.out.println("Lottery numbers: " + picked);
System.out.println("\nShuffle multiple times:");
List<String> items = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
System.out.println("Original: " + items);
for (int i = 0; i < 3; i++) {
Collections.shuffle(items, new Random(seed + 5 + i));
System.out.println("Shuffle " + (i + 1) + ": " + items);
}
}
}
// Collections.shuffle and fill examples
import java.util.*;
public class Shuffle {
public static void main(String[] args) {
int seed = ;
System.out.println("Shuffle list:");
List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
System.out.println("Original: " + nums);
Collections.shuffle(nums, new Random(seed));
System.out.println("Shuffled: " + nums);
System.out.println("\nShuffle with seed:");
List<Integer> nums1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> nums2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Random rand = new Random(seed);
Collections.shuffle(nums1, rand);
rand = new Random(seed);
Collections.shuffle(nums2, rand);
System.out.println("Shuffle 1: " + nums1);
System.out.println("Shuffle 2: " + nums2);
System.out.println("Same? " + nums1.equals(nums2));
System.out.println("\nShuffle deck:");
List<String> deck = new ArrayList<>();
String[] suits = {"♠", "♥", "♦", "♣"};
String[] ranks = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
for (String suit : suits) {
for (String rank : ranks) {
deck.add(rank + suit);
}
}
System.out.println("Deck size: " + deck.size());
System.out.println("First 13: " + deck.subList(0, 13));
Collections.shuffle(deck, new Random(seed + 1));
System.out.println("After shuffle: " + deck.subList(0, 13));
System.out.println("\nDeal cards:");
Collections.shuffle(deck, new Random(seed + 2));
for (int player = 0; player < 4; player++) {
List<String> hand = deck.subList(player * 5, (player + 1) * 5);
System.out.println("Player " + (player + 1) + ": " + hand);
}
System.out.println("\nFill list:");
List<Integer> values = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("Original: " + values);
Collections.fill(values, 0);
System.out.println("Filled with 0: " + values);
System.out.println("\nFill strings:");
List<String> words = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
System.out.println("Original: " + words);
Collections.fill(words, "X");
System.out.println("Filled: " + words);
System.out.println("\nInitialize with fill:");
List<Boolean> flags = new ArrayList<>(10);
for (int i = 0; i < 10; i++) flags.add(null);
Collections.fill(flags, true);
System.out.println("Flags: " + flags);
System.out.println("\nRandom sample:");
List<Integer> population = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
population.add(i);
}
Collections.shuffle(population, new Random(seed + 3));
List<Integer> sample = population.subList(0, 10);
Collections.sort(sample);
System.out.println("Random sample of 10: " + sample);
System.out.println("\nLottery numbers:");
List<Integer> lottery = new ArrayList<>();
for (int i = 1; i <= 49; i++) {
lottery.add(i);
}
Collections.shuffle(lottery, new Random(seed + 4));
List<Integer> picked = new ArrayList<>(lottery.subList(0, 6));
Collections.sort(picked);
System.out.println("Lottery numbers: " + picked);
System.out.println("\nShuffle multiple times:");
List<String> items = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
System.out.println("Original: " + items);
for (int i = 0; i < 3; i++) {
Collections.shuffle(items, new Random(seed + 5 + i));
System.out.println("Shuffle " + (i + 1) + ": " + items);
}
}
}
// Collections.shuffle and fill examples
import java.util.*;
public class Shuffle {
public static void main(String[] args) {
int seed = ;
System.out.println("Shuffle list:");
List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
System.out.println("Original: " + nums);
Collections.shuffle(nums, new Random(seed));
System.out.println("Shuffled: " + nums);
System.out.println("\nShuffle with seed:");
List<Integer> nums1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
List<Integer> nums2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Random rand = new Random(seed);
Collections.shuffle(nums1, rand);
rand = new Random(seed);
Collections.shuffle(nums2, rand);
System.out.println("Shuffle 1: " + nums1);
System.out.println("Shuffle 2: " + nums2);
System.out.println("Same? " + nums1.equals(nums2));
System.out.println("\nShuffle deck:");
List<String> deck = new ArrayList<>();
String[] suits = {"♠", "♥", "♦", "♣"};
String[] ranks = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
for (String suit : suits) {
for (String rank : ranks) {
deck.add(rank + suit);
}
}
System.out.println("Deck size: " + deck.size());
System.out.println("First 13: " + deck.subList(0, 13));
Collections.shuffle(deck, new Random(seed + 1));
System.out.println("After shuffle: " + deck.subList(0, 13));
System.out.println("\nDeal cards:");
Collections.shuffle(deck, new Random(seed + 2));
for (int player = 0; player < 4; player++) {
List<String> hand = deck.subList(player * 5, (player + 1) * 5);
System.out.println("Player " + (player + 1) + ": " + hand);
}
System.out.println("\nFill list:");
List<Integer> values = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println("Original: " + values);
Collections.fill(values, 0);
System.out.println("Filled with 0: " + values);
System.out.println("\nFill strings:");
List<String> words = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
System.out.println("Original: " + words);
Collections.fill(words, "X");
System.out.println("Filled: " + words);
System.out.println("\nInitialize with fill:");
List<Boolean> flags = new ArrayList<>(10);
for (int i = 0; i < 10; i++) flags.add(null);
Collections.fill(flags, true);
System.out.println("Flags: " + flags);
System.out.println("\nRandom sample:");
List<Integer> population = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
population.add(i);
}
Collections.shuffle(population, new Random(seed + 3));
List<Integer> sample = population.subList(0, 10);
Collections.sort(sample);
System.out.println("Random sample of 10: " + sample);
System.out.println("\nLottery numbers:");
List<Integer> lottery = new ArrayList<>();
for (int i = 1; i <= 49; i++) {
lottery.add(i);
}
Collections.shuffle(lottery, new Random(seed + 4));
List<Integer> picked = new ArrayList<>(lottery.subList(0, 6));
Collections.sort(picked);
System.out.println("Lottery numbers: " + picked);
System.out.println("\nShuffle multiple times:");
List<String> items = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E"));
System.out.println("Original: " + items);
for (int i = 0; i < 3; i++) {
Collections.shuffle(items, new Random(seed + 5 + i));
System.out.println("Shuffle " + (i + 1) + ": " + items);
}
}
}
Frequency and Statistics
Count occurrences and find min/max values.
Frequency.java
// Collections.frequency and other counting methods
import java.util.*;
public class Frequency {
public static void main(String[] args) {
System.out.println("Frequency:");
List<String> words = Arrays.asList("apple", "banana", "apple", "cherry", "banana", "apple");
System.out.println("Words: " + words);
System.out.println("'apple': " + Collections.frequency(words, "apple"));
System.out.println("'banana': " + Collections.frequency(words, "banana"));
System.out.println("'cherry': " + Collections.frequency(words, "cherry"));
System.out.println("'grape': " + Collections.frequency(words, "grape"));
System.out.println("\nCount duplicates:");
List<Integer> nums = Arrays.asList(1, 2, 2, 3, 3, 3, 4, 4, 4, 4);
Set<Integer> unique = new HashSet<>(nums);
System.out.println("Numbers: " + nums);
for (int n : unique) {
int count = Collections.frequency(nums, n);
System.out.println(n + " appears " + count + " times");
}
System.out.println("\nDisjoint check:");
List<Integer> list1 = Arrays.asList(1, 2, 3, 4);
List<Integer> list2 = Arrays.asList(5, 6, 7, 8);
List<Integer> list3 = Arrays.asList(3, 4, 5, 6);
System.out.println("List 1: " + list1);
System.out.println("List 2: " + list2);
System.out.println("List 3: " + list3);
System.out.println("1 and 2 disjoint? " + Collections.disjoint(list1, list2));
System.out.println("1 and 3 disjoint? " + Collections.disjoint(list1, list3));
System.out.println("\nBinary search:");
List<Integer> sorted = new ArrayList<>(Arrays.asList(1, 3, 5, 7, 9, 11, 13));
System.out.println("List: " + sorted);
System.out.println("Search 7: " + Collections.binarySearch(sorted, 7));
System.out.println("Search 8: " + Collections.binarySearch(sorted, 8));
System.out.println("\nIndex of sublist:");
List<Integer> main = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
List<Integer> sub1 = Arrays.asList(3, 4, 5);
List<Integer> sub2 = Arrays.asList(5, 6, 7);
List<Integer> sub3 = Arrays.asList(9, 10);
System.out.println("Main: " + main);
System.out.println("Sub [3,4,5]: " + Collections.indexOfSubList(main, sub1));
System.out.println("Sub [5,6,7]: " + Collections.indexOfSubList(main, sub2));
System.out.println("Sub [9,10]: " + Collections.indexOfSubList(main, sub3));
System.out.println("\nLast index of sublist:");
List<Integer> repeated = Arrays.asList(1, 2, 3, 1, 2, 3, 1, 2, 3);
List<Integer> pattern = Arrays.asList(1, 2, 3);
System.out.println("List: " + repeated);
System.out.println("Pattern: " + pattern);
System.out.println("First occurrence: " + Collections.indexOfSubList(repeated, pattern));
System.out.println("Last occurrence: " + Collections.lastIndexOfSubList(repeated, pattern));
System.out.println("\nReplace all:");
List<String> items = new ArrayList<>(Arrays.asList("a", "b", "c", "b", "d", "b"));
System.out.println("Original: " + items);
boolean changed = Collections.replaceAll(items, "b", "X");
System.out.println("Replaced 'b' -> 'X': " + items);
System.out.println("Changed? " + changed);
System.out.println("\nMin and max:");
List<Integer> values = Arrays.asList(42, 17, 93, 8, 56, 31);
System.out.println("Values: " + values);
System.out.println("Min: " + Collections.min(values));
System.out.println("Max: " + Collections.max(values));
System.out.println("\nMin/max with comparator:");
List<String> names = Arrays.asList("Alice", "Bob", "Christopher", "Di");
System.out.println("Names: " + names);
System.out.println("Shortest: " + Collections.min(names, Comparator.comparingInt(String::length)));
System.out.println("Longest: " + Collections.max(names, Comparator.comparingInt(String::length)));
System.out.println("\nMost frequent element:");
List<String> data = Arrays.asList("a", "b", "a", "c", "a", "b", "d", "a");
System.out.println("Data: " + data);
Set<String> uniqueData = new HashSet<>(data);
String mostFrequent = null;
int maxFreq = 0;
for (String item : uniqueData) {
int freq = Collections.frequency(data, item);
if (freq > maxFreq) {
maxFreq = freq;
mostFrequent = item;
}
}
System.out.println("Most frequent: '" + mostFrequent + "' (" + maxFreq + " times)");
}
}
Frequency
Collections.frequency() counts how many times an element appears, useful for finding modes or duplicates.
Unmodifiable Collections
Create read-only views to protect data from modification.
Unmodifiable.java
// Unmodifiable collections
import java.util.*;
public class Unmodifiable {
public static void main(String[] args) {
System.out.println("Unmodifiable list:");
List<String> mutable = new ArrayList<>(Arrays.asList("a", "b", "c"));
List<String> immutable = Collections.unmodifiableList(mutable);
System.out.println("Mutable: " + mutable);
System.out.println("Immutable: " + immutable);
// Modify mutable (reflects in immutable)
mutable.add("d");
System.out.println("After adding to mutable:");
System.out.println("Mutable: " + mutable);
System.out.println("Immutable: " + immutable);
// Try to modify immutable
try {
immutable.add("e");
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify immutable: " + e.getClass().getSimpleName());
}
System.out.println("\nUnmodifiable set:");
Set<Integer> mutableSet = new HashSet<>(Arrays.asList(1, 2, 3));
Set<Integer> immutableSet = Collections.unmodifiableSet(mutableSet);
System.out.println("Set: " + immutableSet);
try {
immutableSet.add(4);
} catch (UnsupportedOperationException e) {
System.out.println("Cannot add to unmodifiable set");
}
System.out.println("\nUnmodifiable map:");
Map<String, Integer> mutableMap = new HashMap<>();
mutableMap.put("Alice", 85);
mutableMap.put("Bob", 92);
Map<String, Integer> immutableMap = Collections.unmodifiableMap(mutableMap);
System.out.println("Map: " + immutableMap);
try {
immutableMap.put("Charlie", 78);
} catch (UnsupportedOperationException e) {
System.out.println("Cannot modify unmodifiable map");
}
System.out.println("\nDefensive copy:");
List<String> original = new ArrayList<>(Arrays.asList("x", "y", "z"));
List<String> defensiveCopy = Collections.unmodifiableList(new ArrayList<>(original));
System.out.println("Original: " + original);
System.out.println("Defensive: " + defensiveCopy);
// Modify original (doesn't affect defensive copy)
original.add("w");
System.out.println("After modifying original:");
System.out.println("Original: " + original);
System.out.println("Defensive: " + defensiveCopy);
System.out.println("\nEmpty collections:");
List<String> emptyList = Collections.emptyList();
Set<Integer> emptySet = Collections.emptySet();
Map<String, Integer> emptyMap = Collections.emptyMap();
System.out.println("Empty list: " + emptyList);
System.out.println("Empty set: " + emptySet);
System.out.println("Empty map: " + emptyMap);
try {
emptyList.add("item");
} catch (UnsupportedOperationException e) {
System.out.println("Empty collections are immutable");
}
System.out.println("\nSingleton collections:");
List<String> singletonList = Collections.singletonList("only");
Set<Integer> singletonSet = Collections.singleton(42);
Map<String, Integer> singletonMap = Collections.singletonMap("key", 100);
System.out.println("Singleton list: " + singletonList);
System.out.println("Singleton set: " + singletonSet);
System.out.println("Singleton map: " + singletonMap);
try {
singletonList.add("another");
} catch (UnsupportedOperationException e) {
System.out.println("Singleton collections are immutable");
}
System.out.println("\nChecked collections:");
List<String> checkedList = Collections.checkedList(
new ArrayList<>(), String.class
);
checkedList.add("valid");
System.out.println("Checked list: " + checkedList);
// Type checking at runtime
@SuppressWarnings("unchecked")
List raw = checkedList;
try {
raw.add(123); // Wrong type
} catch (ClassCastException e) {
System.out.println("Type checking prevented adding Integer to String list");
}
System.out.println("\nSynchronized collections:");
List<Integer> syncList = Collections.synchronizedList(new ArrayList<>());
syncList.add(1);
syncList.add(2);
syncList.add(3);
// Must synchronize on iteration
synchronized (syncList) {
for (int n : syncList) {
System.out.print(n + " ");
}
}
System.out.println("\nSynchronized collections are thread-safe");
}
}
@seealso arrays_util
Unmodifiable view
A wrapper that throws UnsupportedOperationException on modification attempts, protecting the underlying collection.
Exercise: Practical.java
Find the most common word in a list and create a read-only leaderboard