Java 10 - Copy List into Another List Exmaple

In this example, we will see how to copy List into another List using Java 10.

Using Java 10

Finally, Java 10 version allows us to create an immutable list containing the elements of the given Collection:
package net.javaguides.examples;

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

/**
 * Different ways to copy a list into another list
 * 
 * @author Ramesh Fadatare
 *
 */
public class CopyListExamples {

    public static void main(String[] args) {

        List < String > fruits = new ArrayList < > ();
        // Adding new elements to the ArrayList
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("mango");
        fruits.add("orange");
        System.out.println(fruits);

        // using Java 8 copyOf() method
        List < String > copy = List.copyOf(fruits);
        System.out.println(copy);
    }
}
Output:
[Banana, Apple, mango, orange]
[Banana, Apple, mango, orange]
Checkout Copy a List to Another List in Java (5 Ways) - 5 different ways to copy a List to another List with an example.
  1. Using Constructor
  2. Using addAll() method
  3. Using Collections.copy() method
  4. Using Java 8
  5. Using Java 10

References

https://www.javaguides.net/2020/02/copy-list-to-another-list-in-java-5-ways.html

Java ArrayList Source Code Examples


Comments