STUDYECRAT Java 9 Collection Factory Methods
60s
Java -9 Collection Factory Methods
Prove your skills in this interactive quiz
Live Code
Run snippets directly
Timed
60s per question
Scored
Earn 3D badges
★ Java 9 Collection Factory Methods: Key Interview Points
1. Creating Immutable Lists
List<String> colors = List.of("Red", "Green", "Blue");
System.out.println(colors); // Output: [Red, Green, Blue]
System.out.println(colors); // Output: [Red, Green, Blue]
- Tip: These lists are immutable - any modification attempt throws UnsupportedOperationException
- Real Use: Perfect for storing constant values like configuration parameters or enum-like collections
2. Handling Duplicates in Sets
Set<Integer> numbers = Set.of(1, 2, 3, 2);
// Throws IllegalArgumentException: duplicate element: 2
// Throws IllegalArgumentException: duplicate element: 2
- Tip: Always validate data for duplicates before using Set.of()
- Real Use: Ensures data integrity when working with unique identifiers or constraints
3. Compact Map Initialization
Map<String, Integer> ageMap = Map.of(
"Alice", 25,
"Bob", 30,
"Charlie", 35
);
// Creates immutable map with 3 entries
"Alice", 25,
"Bob", 30,
"Charlie", 35
);
// Creates immutable map with 3 entries
- Tip: For more than 10 entries, use Map.ofEntries() with Map.entry()
- Real Use: Ideal for creating constant lookup tables or configuration maps
4. Strict Null Rejection
List<String> list = List.of("A", null, "B");
// Throws NullPointerException immediately
// Throws NullPointerException immediately
- Tip: Always perform null checks before using factory methods
- Real Use: Prevents null-related bugs in applications by failing fast
5. Optimized Empty Collections
List<String> empty1 = List.of();
List<String> empty2 = List.of();
System.out.println(empty1 == empty2); // true - same instance reused
List<String> empty2 = List.of();
System.out.println(empty1 == empty2); // true - same instance reused
- Tip: Always prefer List.of() over new ArrayList() for empty collections
- Real Use: Reduces memory footprint in applications that frequently use empty collections
6. Space-Optimized Implementations
List<String> single = List.of("Single");
System.out.println(single.getClass().getName());
// Output: java.util.ImmutableCollections$List1
System.out.println(single.getClass().getName());
// Output: java.util.ImmutableCollections$List1
- Tip: Java uses specialized implementations for small collections (List1, List2, etc.)
- Real Use: Provides memory efficiency for small, frequently used collections
💡 Pro Interview Tip
When discussing Java 9 collection factories, emphasize their three key advantages: immutability guarantees, null-safety, and memory efficiency. These make them preferable to traditional collection constructors in most cases where modification isn't required.
Tags