Immutable Collection likes an Immutable Object, once created, we can not edit anything on that Object or Collection. From Java 8 and earlier, to initialize an Immutable Collection like List, Set, or Map, we will use the unmodifiableXXX() methods in the java.util.Collections class.
For example, we create an immutable object of List as follows:
1 2 3 4 |
List<String> students = new ArrayList<String>(); students.add("Khanh"); students.add("Quan"); students = Collections.unmodifiableList(students); |
If now, you want to add new value to the students object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.huongdanjava.immutablecollection; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Application { public static void main(String[] args) { List<String> students = new ArrayList<String>(); students.add("Khanh"); students.add("Quan"); students = Collections.unmodifiableList(students); System.out.println(students); students.add("Thanh"); } } |
below error will happen:
From Java 9, Java adds new static method of() to List, Set, Map object, which makes it easier to initialize the Immutable Collection.
For example, now to initialize an Immutable List, we just need to write code like this:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava.immutablecollection; import java.util.List; public class Application { public static void main(String[] args) { List<String> students = List.of("Khanh", "Quan"); System.out.println(students); } } |
With an Immutable Set, it is still same like with Immutable List:
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.huongdanjava.immutablecollection; import java.util.Set; public class Application { public static void main(String[] args) { Set<String> students = Set.of("Khanh", "Quan"); System.out.println(students); } } |
With Immutable Map, there is a little different. For example, from Java 8 and earlier, we will write:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.huongdanjava.immutablecollection; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class Application { public static void main(String[] args) { Map<String, String> students = new HashMap<>(); students.put("A", "Khanh"); students.put("B", "Quan"); students = Collections.unmodifiableMap(students); System.out.println(students); } } |
But for Java 9, we can write down the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package com.huongdanjava.immutablecollection; import java.util.Map; public class Application { public static void main(String[] args) { Map<String, String> students = Map.of("A", "Khanh", "B", "Quan"); System.out.println(students); } } |
As you can see with the Immutable Map, we will pass to the static method of(), key and value of the Map in order (key1, value1, key2, value2, …).
Result: