Java 8 - Copy List into Another List Example

In this post, we will see how to copy List into another List using Java 8 stream.

Using Java 8

Let's use Java 8 Stream APIs to copy List into another List:
package net.javaguides.examples; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /**  * 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 Stream APIs List < String > copy = fruits.stream() .collect(Collectors.toList()); 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

Comments