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

References

  1. Unmodifiable Lists, Sets, and Maps
  2. Different ways to iterate/loop a List of Integers in Java

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.