In this post, we will see how to copy List into another List using Java 8 stream.
https://www.javaguides.net/2020/02/copy-list-to-another-list-in-java-5-ways.html
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.
- Using Constructor
- Using addAll() method
- Using Collections.copy() method
- Using Java 8
- Using Java 10
References
ArrayList Collection Framework Java Java 8
Comments
Post a Comment