Java
java.util.List
list copy
Java programming
collections framework

How to copy a java.util.List into another java.util.List

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Copying a java.util.List into another java.util.List is a common task in Java programming. This operation is essential when you need to duplicate data, manipulate list contents independently, or ensure thread-safety by working with a separate list. Several methods and strategies exist for copying lists effectively, each with its own use cases and implications.

Using the addAll() Method

One straightforward way to copy a list is using the addAll() method, which is a part of the Collection interface. The addAll() method copies all of the elements from one list to another, effectively merging the two lists.

Example

java
1import java.util.ArrayList;
2import java.util.List;
3
4public class ListCopyExample {
5    public static void main(String[] args) {
6        List<String> originalList = new ArrayList<>();
7        originalList.add("A");
8        originalList.add("B");
9        originalList.add("C");
10
11        List<String> copiedList = new ArrayList<>();
12        copiedList.addAll(originalList);
13
14        System.out.println("Original List: " + originalList);
15        System.out.println("Copied List: " + copiedList);
16    }
17}

Key Points

  • Method Simplicity: The addAll() method is straightforward and easy to use.
  • Mutable Copy: The copied list is mutable, meaning that modifications to the copied list do not affect the original.
  • Flat Copy: addAll() performs a shallow copy, copying only references, not the actual objects.

Using the Collections.copy() Method

java.util.Collections provides a static method copy() that creates a copy of one list to another. However, the destination list must be at least as large as the source list.

Example

java
1import java.util.ArrayList;
2import java.util.Collections;
3import java.util.List;
4
5public class CollectionsCopyExample {
6    public static void main(String[] args) {
7        List<String> originalList = new ArrayList<>();
8        originalList.add("A");
9        originalList.add("B");
10        originalList.add("C");
11
12        List<String> copiedList = new ArrayList<>(originalList.size());
13        Collections.addAll(copiedList, new String[originalList.size()]);
14        Collections.copy(copiedList, originalList);
15
16        System.out.println("Original List: " + originalList);
17        System.out.println("Copied List: " + copiedList);
18    }
19}

Key Points

  • Pre-size Requirement: The destination list must be pre-sized to accommodate all elements from the source.
  • Shallow Copy: Similar to addAll(), this method does a shallow copy.
  • Useful for Fixed-Size Lists: This method is particularly useful for lists with fixed sizes.

Using Stream API

Java 8 introduced the Stream API, providing a modern and functional approach to working with collections. Streams can be used to create a new list by collecting elements from a source list.

Example

java
1import java.util.ArrayList;
2import java.util.List;
3import java.util.stream.Collectors;
4
5public class StreamCopyExample {
6    public static void main(String[] args) {
7        List<String> originalList = new ArrayList<>();
8        originalList.add("A");
9        originalList.add("B");
10        originalList.add("C");
11
12        List<String> copiedList = originalList.stream()
13                                              .collect(Collectors.toList());
14
15        System.out.println("Original List: " + originalList);
16        System.out.println("Copied List: " + copiedList);
17    }
18}

Key Points

  • Conciseness: Using streams offers a clean and concise way to copy lists.
  • Immutability: While the copied list is mutable, streams can be used in more functional, immutable styles if needed.
  • Parallel Processing: Streams support parallel operations, which can be beneficial for performance.

Arrays to List

Another way to copy a list is to convert it to an array and then back to a list. This is more convoluted but demonstrates flexibility.

Example

java
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.List;
4
5public class ArrayToListExample {
6    public static void main(String[] args) {
7        List<String> originalList = new ArrayList<>();
8        originalList.add("A");
9        originalList.add("B");
10        originalList.add("C");
11
12        String[] array = originalList.toArray(new String[0]);
13        List<String> copiedList = new ArrayList<>(Arrays.asList(array));
14
15        System.out.println("Original List: " + originalList);
16        System.out.println("Copied List: " + copiedList);
17    }
18}

Conclusion

Copying lists efficiently and correctly requires understanding of the underlying mechanics of different methods. Here's a summary of the discussed methods:

MethodMutabilityCopy TypeConcisenessRequires Pre-sizingNotes
addAll()MutableShallowSimpleNoEasy and straightforward
Collections.copy()MutableShallowModerateYesUseful for fixed-size destination
Stream APIMutableShallowHighNoOffers parallel processing capabilities
Arrays to ListMutableShallowComplexNoDemonstrates flexibility

Understanding these methods allows developers to choose the most appropriate one depending on performance and design requirements.


Course illustration
Course illustration

All Rights Reserved.