[From JDK8 to JDK21]: Beginner guide and Examples of List.of(),Map.Of() since jdk9
1. Purpose
In this post, I will show you how to use List.of() and Map.of() since jdk9, these two methods are introduced in jdk9 to create unmodifiable collections.
2. What is unmodifiable collections?(or immutable collections)
unmodifiable collections are collections that cannot be modified after creation. You can not add, remove or modify elements in the collection after creation.
They are useful when you want to ensure that the collection remains unchanged throughout the program.
2. Before jdk9
Before jdk9, we can use the following code to create an unmodifiable list:
List<String> theList = new ArrayList<>();theList.add("apple");theList.add("banana");List<String> list = Collections.unmodifiableList(theList); //then the list is unmodifiableTo create an unmodifiable map before jdk9, we can use the following code:
Map<String, Integer> theMap = new HashMap<>();theMap.put("apple", 1);theMap.put("banana", 2);Map<String, Integer> map = Collections.unmodifiableMap(theMap);3. After jdk9: the new List.of() and Map.of() methods
3.1 List.of()
List.of() is a static method introduced in jdk9 to create an unmodifiable list.
here is an example:
List<String> list = List.of("apple", "banana");The List.of() method takes a variable number of arguments, which means you can pass any number of elements to it.
3.2 Map.of()
Map.of() is a static method introduced in jdk9 to create an unmodifiable map. here is an example:
Map<String, Integer> map = Map.of("apple", 1, "banana", 2);Or you can also use Map.ofEntries() to create an unmodifiable map:
Map<String, Integer> map = Map.ofEntries( Map.entry("apple", 1), Map.entry("banana", 2));3.3 Set.of()
Set.of() is a static method introduced in jdk9 to create an unmodifiable set.
here is an example:
Set<String> set = Set.of("apple", "banana");5. Summary
That’s it, thnkas for reading.
Final Words + More Resources
My intention with this article was to help others share my knowledge and experience. If you want to contact me, you can contact by email: Email me
Here are also the most important links from this article along with some further resources that will help you in this scope:
Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!