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]

Updated on: 10-May-2022

528 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements