To concatenate two lists in Java, you can use the addAll
method of the List
interface.
In this example,
list1
and list2
with initial values.addAll
method to append all elements of list2
to list1
.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = List.of(4, 5, 6);
list1.addAll(list2);
System.out.println("Concatenated list: " + list1);
}
}
Concatenated list: [4, 5, 6]
In this example,
list1
and list2
with initial values.Stream
API to concatenate the elements of list2
to list1
.import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> list1 = new ArrayList<>();
List<Integer> list2 = List.of(4, 5, 6);
list1.addAll(list2.stream().collect(Collectors.toList()));
System.out.println("Concatenated list: " + list1);
}
}
Concatenated list: [4, 5, 6]
In this tutorial, we learned How to Concatenate Two Lists in Java language with well detailed examples.