2

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

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


Daniel Hári
  • 7,254
  • 5
  • 39
  • 54

3 Answers3

3

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());
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
-1

Yeah you can simply use the java.util.Arrays class for single and multiple elements.

List<String> strings = Arrays.asList("first", "second", "third");

You can use the java.util.Collections for a list with a single element.

List<String> strings = Collections.singletonList("first");
Jason
  • 5,154
  • 2
  • 12
  • 22
-1

If you wanna copy list, you can do it by constructor like this

List<Float> oldList = new ArrayList<>();
List<Float> newList = new ArrayList<>(oldList);
Bogus
  • 283
  • 1
  • 2
  • 13