I was just wondering that if java has the equivalent of arrayof()/ listof()/ setof()/ mapof() like those in kotlin? If not, is there any way to work similarly? I found them
Java 9 brings similar methods: List#of, Set#of, Map#of with several overloaded methods to avoid calling the varargs one. In case of Map
, for varargs, you have to use Map#ofEntries.
Pre Java 9, you had to use Arrays#asList
as entry point to initialize List
and Set
:
List<String> list = Arrays.asList("hello", "world");
Set<String> set = new HashSet<>(Arrays.asList("hello", "world"));
And if you wanted your Set
to be immutable, you had to wrap it inside an immutable set from Collections#unmodifiableSet:
Set<String> set = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList("hello", "world")));
For Map, you may use a trick creating an anonymous class that extended a Map
implementation, and then wrap it inside Collections#unmodifiableMap. Example:
Map<String, String> map = Collections.unmodifiableMap(
//since it's an anonymous class, it cannot infer the
//types from the content
new HashMap<String, String>() {{
put.("hello", "world");
}})
);