Search code examples
javalistarraylistjava-8guava

List initialialization with a first element and an additional collection


Is there a shorthand way (may be guava or any lib) to initialize a Java List like this?

List list = MagicListUtil.newArrayList(firstElement, moreElementsList);



Solution

  • Guava offers several possibilities

    If you have arrays, use Lists.asList(...)

    String first = "first";
    String[] rest = { "second", "third" };
    List<String> list = Lists.asList(first, rest);
    

    If you have lists or other Iterables, use FluentIterable.of(...).append(...).toList():

    String first = "first";
    List<String> rest = Arrays.asList("second", "third");
    List<String> list = FluentIterable.of(first).append(rest).toList();
    

    But you can do that in Java 8 as well

    Even though, it's way more verbose, but still...

    With an array

    String first = "first";
    String[] rest = { "second", "third" };
    List<String> list = Stream.concat(Stream.of(first), Arrays.stream(rest))
      .collect(Collectors.toList());
    

    With a Collection

    String first = "first";
    List<String> rest = Arrays.asList("second", "third");
    List<String> list = Stream.concat(Stream.of(first), rest.stream())
      .collect(Collectors.toList());