1

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?

2
  • You can also use Collections.unmodifiableList() Commented Aug 4, 2018 at 15:55
  • @KrishnaSharma That's completely different from an immutable list. Commented Aug 4, 2018 at 16:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.