Nearby lessons

98 of 125

Java - Factory Methods for Collections

📌 What You Will Learn
  • JShell — the interactive Java playground
  • Modules (JPMS) — the big architecture change
  • Private methods in interfaces
  • Factory methods for collections: List.of, Set.of, Map.of
  • The updated try-with-resources

Factory Methods for Collections is a core concept of the Java language. This lesson explains Factory Methods for Collections with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Factory Methods for Collections

Creating a small fixed collection became super short. List.of, Set.of and Map.of create immutable collections (cannot be changed afterwards).

In simple words: `List.of`, `Set.of` and `Map.of` build a fixed collection in one short line, and that collection is immutable — any add, remove or set on it throws UnsupportedOperationException.
Trainer's Note: These collections are immutable — cities.add("Goa") will throw UnsupportedOperationException. They are perfect for fixed lists like days of the week or menu options. (They replace the old, verbose Arrays.asList patterns.)
Example01
JCode Cell
1import java.util.*;
2 
3class FactoryDemo {
4 public static void main(String[] args) {
5 List<String> cities = List.of("Delhi", "Mumbai", "Pune");
6 Set<Integer> nums = Set.of(1, 2, 3);
7 Map<String, Integer> marks = Map.of("Rahul", 88, "Priya", 95);
8 
9 System.out.println(cities);
10 System.out.println(nums);
11 System.out.println(marks);
12 }
13}
Output
[Delhi, Mumbai, Pune] [1, 2, 3] {Rahul=88, Priya=95}
📝 Key Takeaways
  • JShell lets you test Java interactively without files.
  • JPMS modules group packages with clear exports and requirements.
  • Interfaces can now have private helper methods.
  • List.of / Set.of / Map.of create short, immutable collections.
  • try-with-resources can use existing variables (Java 9).
  • New stream helpers: Optional.stream(), Stream.ofNullable().

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2