List initialialization with a first element and an additional collection

Daniel Hári :

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

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


Olivier Grégoire :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325411&siteId=1