To append a list to another list 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
.list1
to standard output.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("Updated list: " + list1);
}
}
Updated list: [4, 5, 6]
In this example,
list1
and list2
with initial values.Stream
API to concatenate the elements of list2
to list1
.list1
to standard output.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("Updated list: " + list1);
}
}
Updated list: [4, 5, 6]
In this tutorial, we learned How to Append a List to another List in Java language with well detailed examples.