5

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);
mind_
  • 134
  • 1
  • 9
DerBenniAusA
  • 427
  • 1
  • 3
  • 8
  • 2
    Your expected code is never going to work, there is no way to use the `+` operator to make lists in Java. – Jesper Apr 03 '19 at 12:02
  • it is just a hint to which solution it could lead me. i need a equivalent to this – DerBenniAusA Apr 03 '19 at 12:03
  • You have right code. The addAll() is right call for extending one list by another. In case of jdk8 check here - https://stackoverflow.com/a/18687790/10099219 – PriyankaW Apr 03 '19 at 12:07
  • @PriyankaW mind that OP is working with `ImmutableList`s from (probably) guava, as the name says they're immutable and `addAll` can't be used – Lino Apr 03 '19 at 12:10
  • @Lino thank you for letting me know about guava; i missed to identify that. Then perhaps OP needs to use `ImmutableList.<>builder().addAll()`. – PriyankaW Apr 03 '19 at 12:15

1 Answers1

6

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();
mind_
  • 134
  • 1
  • 9