javaguavaimmutablelist

Extend ImmutableList.of() by another List


I want to simplify existing code that is related to ImmutableList.of() functionality

I alreaday tried to optimize the creation of the second List by eliminating the "new..." constructor, but of course I couldnt extend a immutable list by calling .add();

Current code:

static final ImmutableList<ProductCodeEnum> PRODUCTS = ImmutableList.of(ProductCodeEnum.A, ProductCodeEnum.B, ProductCodeEnum.C);


static final ImmutableList<ProductCodeEnum> PRODUCTS_EXTENDED_LIST = new ImmutableList.Builder<ProductCodeEnum>().addAll(PRODUCTS)
.add(ProductCodeEnum.D)
.add(ProductCodeEnum.E)
.build();

Expected code like:

static final ImmutableList<ProductCodeEnum> PRODUCTS = ImmutableList.of(ProductCodeEnum.A, ProductCodeEnum.B, ProductCodeEnum.C);


static final ImmutableList<ProductCodeEnum> PRODUCTS_EXTENDED = PRODUCTS + ImmutableList.of(ProductCodeEnum.D, ProductCodeEnum.E);

Solution

  • I think you use Guava ImmutableList?

    In that case your code would look like this:

    static final ImmutableList<ProductCodeEnum> PRODUCTS = ImmutableList.of(ProductCodeEnum.A, ProductCodeEnum.B, ProductCodeEnum.C);
    
    static final ImmutableList<ProductCodeEnum> PRODUCTS_EXTENDED = ImmutableList.builder().addAll(PRODUCTS).add(ProductCodeEnum.D, ProductCodeEnum.E).build();