Java 8 clone ArrayList with elements

In Java 8 it's possible to clone ArrayList by two ways using methods:

  • toCollection()
  • toList()
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;

List<String> copy = Arrays.asList("A1",	"A2",	"A3",	"A4",	"A5",	"A6",	"A7");
copy1 = copy.stream().map(String::new).collect(toList());
copy2 = copy.stream().map(String::new).collect(toCollection(ArrayList::new));

Example showing the two clone methods :

package collection;

import java.util.*;

import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;

public class TestClone {
    public static void main(String[] args) {
        List<String> copy = Arrays.asList("A1",	"A2",	"A3",	"A4",	"A5",	"A6",	"A7");
        List<String> copy1 = cloneArrayList(copy);
        List<String> copy2 = cloneArrayList2(copy);
        printArrayList(copy1);
        printArrayList(copy2);
    }


    //
    // clone by using toCollection
    //
    public static final ArrayList<String> cloneArrayList(List<String> list) {
        return list.stream().map(String::new).collect(toCollection(ArrayList::new));
    }
    //
    // clone by using toList
    //
    public static final List<String> cloneArrayList2(List<String> list) {
        return list.stream().map(String::new).collect(toList());
    }
    //
    // print ArrayList comma separatorated
    //
    public static final void printArrayList(List<String> list) {
        for (String temp : list) {
            System.out.print(temp + ", ");
        }
        System.out.println();
    }
}

You may want to check:

Note

Changing return type of the method from List to ArrayList will cause error. So changing this method:

public static final List<String> cloneArrayList2(List<String> list) {
    return list.stream().map(String::new).collect(toList());
}

to

public static final ArrayList<String> cloneArrayList2(List<String> list) {
    return list.stream().map(String::new).collect(toList());
}

is causing error like

Error:(28, 54) java: incompatible types: inference variable R has incompatible bounds
    equality constraints: java.util.List<java.lang.String>
    upper bounds: java.util.ArrayList<java.lang.String>,java.lang.Object

Related Article