Looking for an ideal way to add values optionally to list. Final list must be immutable.
Example-
Optional<Item> optionalItem = getOptionalItemFromSomewhereElse();
List<Item> list = ImmutableList.builder()
.add(item1)
.add(item2)
.optionallyAdd(optionalItem)
.build();
add(element) " is because this method is designed to be able to add elements to ImmutableList s. Those are, quite obviously, immutable (if you look, their native add method throws an UnsupportedOperationException ) and so the only way to "add" to them is to create a new list.
In Java 8 and earlier versions, we can use collection class utility methods like unmodifiableXXX to create immutable collection objects. If we need to create an immutable list then use the Collections. unmodifiableList() method.
No, you cannot make the elements of an array immutable. But the unmodifiableList() method of the java. util. Collections class accepts an object of the List interface (object of implementing its class) and returns an unmodifiable form of the given object.
I would add the optional item at the end, if it's present:
ImmutableList.Builder<Item> builder = ImmutableList.<Item>builder()
.add(item1)
.add(item2);
optionalItem.ifPresent(builder::add);
After that, I'd build the list:
ImmutableList<Item> list = builder.build();
Assuming you're using Guava, here's a simple one-liner:
List<Item> list = Stream.concat(Stream.of(item1, item2), Streams.stream(optionalItem))
.collect(ImmutableList.toImmutableList());
Note: This requires at minimum Java 8 and Guava 21.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With