Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Add to Guava ImmutableList if optional value is present

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();
like image 250
Skywalker Avatar asked May 11 '17 21:05

Skywalker


People also ask

Can you add to ImmutableList?

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.

Can we create immutable collection in Java and how?

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.

How do you make an Arraylist immutable?

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.


2 Answers

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();
like image 97
fps Avatar answered Oct 05 '22 23:10

fps


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.

like image 30
shmosel Avatar answered Oct 05 '22 23:10

shmosel