- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you copy an element from one list to another in Java?
An element can be copied to another List using streams easily.
Use Streams to copy selective elements.
List<String> copyOfList = list.stream().filter(i -> i % 2 == 0).collect(Collectors.toList());
Example
Following is the example to copy only even numbers from a list −
package com.tutorialspoint; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class CollectionsDemo { public static void main(String[] args) { List<Integer> list = Arrays.asList(11, 22, 3, 48, 57); System.out.println("Source: " + list); List<Integer> evenNumberList = list.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()); System.out.println("Even numbers in the list: " + evenNumberList); } }
Output
This will produce the following result −
Source: [11, 22, 3, 48, 57] Even numbers in the list: [22, 48]
Advertisements