Java Factory Methods

Nuwan Zen
Jul 27, 2021

Creating a small Collection in Java is very verbose using the traditional way.

Set<String> set = new HashSet<>();
set.add("foo");
set.add("bar");
set.add("baz");

Java 9 “of” method comes to rescue us

Set<String> set = Set.of("foo", "bar", "baz");

You can use in other collections as well

List<String> list = List.of("foo", "bar", "baz");
Map<String, String> map = Map.of("foo", "a", "bar", "b", "c");
int[] arr = { 1, 2, 3, 4, 5 };
List<int[]> list = List.of(arr);

--

--

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!