Java 9 finally brings the convenience of creating small unmodifiable Collection instances using just one line code. New APIs make it convenient to create instances of collections and maps with small number of elements.
Driving Factor
Too much code is required to be written to create a small, unmodifiable collection, which involves constructing it, then storing it in a local variable, and calling methods e.g.
Set<String> set = new HashSet<>(); set.add("first"); set.add("second"); set.add("third"); set = Collections.unmodifiableSet(set);
Alternatively one can create same using constructor method.
Set<String> set = Collections.unmodifiableSet (new HashSet<>(Arrays.asList("first", "second", "third")));
Or using Double brace method
Set<String> set = Collections.unmodifiableSet (new HashSet<String>() {{ add("first"); add("second"); add("third");}});
or using Java 8 Streams
Stream.of("first", "second", "third") .collect(collectingAndThen(toSet(), Collections::unmodifiableSet));
New Methods
Java 9 provides static methods for List, Set, and Map interfaces which take the elements as arguments
List<String> list = List.of("first", "second", "third"); Set<String> set = Set.of("first", "second", "third"); Map<Integer, String> map = Map.of(1, "first", 2, "second");
For maps this method is overloaded to have 0 to 10 key-value pairs, e.g.
Map<String, String> map = Map.of("1", "first"); Map<String, String> map = Map.of("1", "first", "2", "second"); Map<String, String> map = Map.of("1", "first", "2", "second", "3", "third");
Similarly you can have up to ten entries.
For a case where we have more than 10 key-value pairs, there is a different method:
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)
Java 9 has definitely made creating collection so easy.
Comments
Post a Comment