Java: Add to Guava ImmutableList if extra value is present

Looking for the perfect way to add enumerable values. The final list should be unchanged.

Example -

Optional<Item> optionalItem = getOptionalItemFromSomewhereElse();

List<Item> list = ImmutableList.builder()
                      .add(item1) 
                      .add(item2)
                      .optionallyAdd(optionalItem)
                  .build();

      

+3


source to share


2 answers


I would add an optional element at the end if present:

ImmutableList.Builder<Item> builder = ImmutableList.<Item>builder()
    .add(item1)
    .add(item2);
optionalItem.ifPresent(builder::add);

      



After that, I'll create a list:

ImmutableList<Item> list = builder.build();

      

+6


source


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 a minimum of Java 8 and Guava 21.

+2


source







All Articles