Home> Java> javaTutorial> body text

How to copy a list in Java?

WBOY
Release: 2023-08-24 17:49:07
forward
1134 people have browsed it

How to copy a list in Java?

There are several ways to copy a list of elements into another list.

Way #1

Create a list by passing another list as a constructor parameter.

List copyOflist = new ArrayList<>(list);
Copy after login

Create a list and add all elements of the source list to it using the addAll method.

Method #2

List copyOfList = new ArrayList<>(); copyOfList.addAll(list);
Copy after login

Method #3

Use the Collections.copy method to copy the contents of the source list to the target list. If an index exists, existing elements will be overwritten.

Collections.copy(copyOfList, list);
Copy after login

Way #4

Use a stream to create a copy of the list.

List copyOfList = list.stream().collect(Collectors.toList());
Copy after login

Example

The following is an example to explain using various methods to create a copy of a List object.

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 list = Arrays.asList(1, 2, 3, 4, 5); System.out.println("Source: " + list); List copyOfList1 = new ArrayList<>(list); System.out.println("Copy 1: " + copyOfList1); List copyOfList2 = new ArrayList<>(); copyOfList2.addAll(list); System.out.println("Copy 2: " + copyOfList2); List copyOfList3 = Arrays.asList(6, 7, 8, 9, 0 ); Collections.copy(copyOfList3, list); System.out.println("Copy 3: " + copyOfList3); List copyOfList4 = list.stream().collect(Collectors.toList()); System.out.println("Copy 4: " + copyOfList4); } }
Copy after login

Output

This will produce the following results −

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]
Copy after login

The above is the detailed content of How to copy a list in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!