java list add example

In java 8 adding new elements to list is similar to prevois versions:

Java list add

import java.util.ArrayList;

List<String> myList = new ArrayList<>();
myList.add("Java 8 is cool");
myList.add("Java 9 is cool");
myList.add("Java 7 is cool");

result:

[Java 8 is cool, Java 9 is cool, Java 7 is cool]

java list addAll

Adding more than one element to a list is done by method addAll:

import java.util.Arrays;

List<String> yourList = Arrays.asList("Java 8 is cool","Java 9 is cool", "Java 7 is cool");
myList.addAll(yourList);

System.out.println(myList);

result:

[Java 8 is cool, Java 9 is cool, Java 7 is cool]

java list add element with iteration

If you need to add an element to a list while iterating to another list. You can do it as in the example below:

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

List<String> yourList = Arrays.asList("Java 8 is cool","Java 9 is cool", "Java 7 is cool");
List<String> myList = new ArrayList<>();

for (String s : yourList) {
    myList.add(s);
}

System.out.println(myList);

result

[Java 8 is cool, Java 9 is cool, Java 7 is cool]

Related Article