How do you put two lists together in Java?

Asked 2 years ago, Updated 2 years ago, 47 views

Is there a way to combine the two lists as short as possible with JDK without touching the existing list and without using other libraries?

List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);

I wish it was simpler than this sauce.

list java jdk1.5

2022-09-21 23:01

1 Answers

The shortest code that I can squeeze out of my head is

List<String> newList = new ArrayList<String>(listOne); newList.addAll(listTwo);

And if you use another library, use the Apache Commons library and ListUtils.union(list1,list2); You could do this.


2022-09-21 23:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.