

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 a list in Java?
A List of elements can be copied to another List using multiple ways.
Way #1
Create a List by passing another list as a constructor argument.
List<String> copyOflist = new ArrayList<>(list);
Create a List and use addAll method to add all the elements of the source list.
Way #2
List<String> copyOfList = new ArrayList<>(); copyOfList.addAll(list);
Way #3
Use Collections.copy method to copy the contents of source list to destination. Existing elements will be overridden by indexes if any.
Collections.copy(copyOfList, list);
Way #4
Use Streams to create a copy of a list.
List<String> copyOfList = list.stream().collect(Collectors.toList());
Example
Following is the example to explain the creation of copy of List object using multiple ways −
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class CollectionsDemo { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5); System.out.println("Source: " + list); List<Integer> copyOfList1 = new ArrayList<>(list); System.out.println("Copy 1: " + copyOfList1); List<Integer> copyOfList2 = new ArrayList<>(); copyOfList2.addAll(list); System.out.println("Copy 2: " + copyOfList2); List<Integer> copyOfList3 = Arrays.asList(6, 7, 8, 9, 0 ); Collections.copy(copyOfList3, list); System.out.println("Copy 3: " + copyOfList3); List<Integer> copyOfList4 = list.stream().collect(Collectors.toList()); System.out.println("Copy 4: " + copyOfList4); } }
Output
This will produce the following result −
Source: [1, 2, 3, 4, 5] Copy 1: [1, 2, 3, 4, 5] Copy 2: [1, 2, 3, 4, 5] Copy 3: [1, 2, 3, 4, 5] Copy 4: [1, 2, 3, 4, 5]
- Related Questions & Answers
- How do you make a shallow copy of a list in Java?
- How do you copy an element from one list to another in Java?
- How do you create a list in Java?
- How do you make a list iterator in Java?
- How do you copy a Lua table by value?
- How do you do a deep copy of an object in .NET?
- How do you create a list with values in Java?
- How do you create a list from a set in Java?
- How do you turn a list into a Set in Java?
- How do you convert list to array in Java?
- How do you create an empty list in Java?
- How do you check a list contains an item in Java?
- How do you add an element to a list in Java?
- How to copy a list to another list in Java?
- How do we copy objects in java?
Advertisements