how to add all list elements at once in java

how to add all list elements at once in java

To add all the elements of a list to another list in Java, you can use the addAll method of the java.util.List interface. This method adds all the elements of one list to the end of another list.

Here's an example of how you could use the addAll method to add all the elements of a list to another list:

import java.util.ArrayList;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> list1 = new ArrayList<>();
    list1.add("Apple");
    list1.add("Banana");

    List<String> list2 = new ArrayList<>();
    list2.add("Carrot");
    list2.add("Potato");

    list1.addAll(list2); // Add all the elements of list2 to list1

    System.out.println(list1); // [Apple, Banana, Carrot, Potato]
  }
}
Source:w‮l.ww‬autturi.com

In this example, the list1 list contains two strings, and the list2 list contains two other strings. The addAll method is used to add all the elements of the list2 list to the end of the list1 list.

You can use a similar approach to add the elements of any type of list to another list, as long as the elements are compatible with the type of the list.

Keep in mind that the addAll method modifies the original list in place, so it does not return a new list. If you want to create a new list that combines the elements of two lists, you can use the java.util.Stream class and the concat method to create a stream that combines the elements of both lists, and then use the collect method to create a new list from the stream.

For example:

/**
 * @author lautturi.com 
 * Java example:
 */
package hello;

import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Lautturi {
	public static void main(String[] args) {
		List<String> list1 = List.of("Apple", "Banana");
	    List<String> list2 = List.of("Carrot","Potato");
	    
	    Stream<String> mergedStream = Stream.concat(list1.stream(), list2.stream());
	    List<String> mergedList = mergedStream.collect(Collectors.toList());
	    System.out.println(mergedList);
	}
}

output:

[Apple, Banana, Carrot, Potato]
Created Time:2017-11-01 12:05:10  Author:lautturi