Java: Add to Guava ImmutableList if optional value is present
immutability, java, list, option-type
Solution
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();
Problem
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(); ```