0

I am given a list and I want to add a single element of the same type that the list holds

List<String> list = List.of("a", "b", "c");
String item = "d";

I want to create an immutable list from both of them

List<String> combined = List.of(list.toArray(new String[0]), item);

The above of course does not compile because it's looking at the 2 argument overload where one argument is a String[] and the other is a String and want to create a List of size 2. What I want is to use the varargs signature of String, so to combine somehow the item into the array or "explode" the array and then the result will "merge" with the single argument.

What I tried?

List<String> arraylist = new ArrayList<>(list);
arraylist.add(item);
List<String> combined = List.copyOf(arraylist);

This is very inefficient. Can I do better?

Mark
  • 2,167
  • 4
  • 32
  • 64
  • You can also use [Collections.unmodifiableList()](https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableList(java.util.List)) – Krishna Sharma Aug 04 '18 at 15:55
  • @KrishnaSharma That's completely different from an immutable list. – Mark Aug 04 '18 at 16:10

0 Answers0