Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I join two lists in Java?

Tags:

java

list

jdk1.5

Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.

Is there a simpler way than:

List<String> newList = new ArrayList<String>(); newList.addAll(listOne); newList.addAll(listTwo); 
like image 779
Robert Atkins Avatar asked Oct 09 '08 23:10

Robert Atkins


People also ask

How do I merge two array lists?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

How do you join an ArrayList in Java?

To join elements of given ArrayList<String> arrayList with a delimiter string delimiter , use String. join() method. Call String. join() method and pass the delimiter string delimiter followed by the ArrayList<String> arrayList .


1 Answers

In Java 8:

List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())                              .collect(Collectors.toList()); 
like image 60
Dale Emery Avatar answered Sep 21 '22 07:09

Dale Emery