Java 9- Creating Collection using Factory Method of(…)
Java 9 introduced static factory method of(...) to create the unmodifiable collection instance for the List, Set, and Map. It will throw NullPointerException when you will add NULL value and UnsupportedOperationException when you will modify the collection objects.
Java9Collection.java
package org.websparrow;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Java9Collection {
public static void main(String[] args) {
;
// Creating List
List<String> list = List.of("New Delhi", "Mumbai", "Banglore");
// Creating Set
Set<String> set = Set.of("Priyanka", "Sagar", "Shilpa");
// Creating Map
Map<Integer, String> map = Map.of(1, "One", 2, "Two", 3, "Three");
// Retrieving collection values
System.out.println("--------List values------");
list.forEach(System.out::println);
System.out.println("--------Set values------");
set.forEach(System.out::println);
System.out.println("--------Map values------");
map.entrySet().forEach(System.out::println);
}
}Output:
Console
--------List values------
New Delhi
Mumbai
Banglore
--------Set values------
Sagar
Priyanka
Shilpa
--------Map values------
1=One
2=Two
3=Three