Creating lists and sets with fixed elements
One-line initializations for Java lists and sets with given elements.
Initializing an array with fixed elements is straightforward:
new String[] {"a", "b"};
Given some context information, the compiler spares you from redundantly defining the type:
String[] array = {"a", "b"};
If you need lists or sets instead of arrays, you have the choice between several alternatives:
List.of("a", "b");
Stream.of("a", "b").toList();
Stream.of("a", "b").collect(Collectors.toList());
Stream.of("a", "b").collect(Collectors.toCollection(ArrayList::new));
Arrays.asList("a", "b");
Set.of("a", "b");
Stream.of("a", "b").collect(Collectors.toSet());
Stream.of("a", "b").collect(Collectors.toCollection(HashSet::new));
These alternatives behave differently with respect to null elements and mutability, as summarized in the following table:
Method | accepts null | modifiable |
---|---|---|
List.of(...) | no | no |
Stream.of(...).toList() | not guaranteed | no |
Stream.of(...).collect(Collectors.toList()) | not guaranteed | not guaranteed |
Stream.of(...).collect(Collectors.toCollection(...)) | depends1 | depends1 |
Arrays.asList(...) | yes | partly2 |
Set.of(...) | no | no |
Stream.of(...).collect(Collectors.toSet()); | not guaranteed | not guaranteed |
Stream.of(...).collect(Collectors.toCollection(...)) | depends1 | depends1 |
Note #1: Depends on the provided factory method.
Note #2: Mutations that don’t change the list’s size are supported.