Sobes.tech
Junior — Middle

How to implement the operation of merging elements in an ArrayList?

sobes.tech AI

Answer from AI

In Java, to combine elements into an ArrayList, you can use the addAll() method. It adds all elements from another collection to the current list.

Example:

import java.util.ArrayList;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list1 = new ArrayList<>(Arrays.asList("A", "B"));
        ArrayList<String> list2 = new ArrayList<>(Arrays.asList("C", "D"));

        list1.addAll(list2);  // Merging list2 into list1

        System.out.println(list1);  // [A, B, C, D]
    }
}

Thus, addAll() allows for efficient merging of elements from one collection into another.