Copy a List to Another List in Java (5 Ways)

Copying a list to another list in Java can be achieved using various methods. This guide will cover five different approaches to copy a list, explain how they work, and provide examples to demonstrate their functionality. Additionally, we will cover real-world use cases to illustrate their application.

Table of Contents

  1. Introduction
  2. Using the addAll() Method
  3. Using the Collections.copy() Method
  4. Using the Constructor
  5. Using the Stream API (Java 8 and above)
  6. Using a Loop
  7. Real-World Use Case
  8. Conclusion

Introduction

Copying a list in Java can be useful when you need to duplicate or back up a list. Each method has its advantages and specific use cases. Understanding these methods will help you choose the most appropriate one for your needs.

Using the addAll() Method

The addAll() method adds all elements of one list to another. This method is simple and efficient for copying elements.

Example

import java.util.ArrayList;
import java.util.List;

public class AddAllExample {
    public static void main(String[] args) {
        List<String> sourceList = new ArrayList<>();
        sourceList.add("Apple");
        sourceList.add("Banana");
        sourceList.add("Orange");

        List<String> targetList = new ArrayList<>();
        targetList.addAll(sourceList);

        System.out.println("Source list: " + sourceList);
        System.out.println("Target list: " + targetList);
    }
}

Output:

Source list: [Apple, Banana, Orange]
Target list: [Apple, Banana, Orange]

Using the Collections.copy() Method

The Collections.copy() method copies elements from one list into another. The target list must be at least as long as the source list.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionsCopyExample {
    public static void main(String[] args) {
        List<String> sourceList = new ArrayList<>();
        sourceList.add("Apple");
        sourceList.add("Banana");
        sourceList.add("Orange");

        List<String> targetList = new ArrayList<>(sourceList.size());
        // Initialize target list with null values
        for (int i = 0; i < sourceList.size(); i++) {
            targetList.add(null);
        }

        Collections.copy(targetList, sourceList);

        System.out.println("Source list: " + sourceList);
        System.out.println("Target list: " + targetList);
    }
}

Output:

Source list: [Apple, Banana, Orange]
Target list: [Apple, Banana, Orange]

Using the Constructor

You can use a list's constructor to create a new list with the elements of an existing list.

Example

import java.util.ArrayList;
import java.util.List;

public class ConstructorExample {
    public static void main(String[] args) {
        List<String> sourceList = new ArrayList<>();
        sourceList.add("Apple");
        sourceList.add("Banana");
        sourceList.add("Orange");

        List<String> targetList = new ArrayList<>(sourceList);

        System.out.println("Source list: " + sourceList);
        System.out.println("Target list: " + targetList);
    }
}

Output:

Source list: [Apple, Banana, Orange]
Target list: [Apple, Banana, Orange]

Using the Stream API (Java 8 and above)

The Stream API provides a functional approach to copy a list.

Example

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
    public static void main(String[] args) {
        List<String> sourceList = new ArrayList<>();
        sourceList.add("Apple");
        sourceList.add("Banana");
        sourceList.add("Orange");

        List<String> targetList = sourceList.stream().collect(Collectors.toList());

        System.out.println("Source list: " + sourceList);
        System.out.println("Target list: " + targetList);
    }
}

Output:

Source list: [Apple, Banana, Orange]
Target list: [Apple, Banana, Orange]

Using a Loop

You can manually copy elements from one list to another using a loop. This method provides more control over the copying process.

Example

import java.util.ArrayList;
import java.util.List;

public class LoopExample {
    public static void main(String[] args) {
        List<String> sourceList = new ArrayList<>();
        sourceList.add("Apple");
        sourceList.add("Banana");
        sourceList.add("Orange");

        List<String> targetList = new ArrayList<>();
        for (String item : sourceList) {
            targetList.add(item);
        }

        System.out.println("Source list: " + sourceList);
        System.out.println("Target list: " + targetList);
    }
}

Output:

Source list: [Apple, Banana, Orange]
Target list: [Apple, Banana, Orange]

Real-World Use Case

Duplicating a List of Users

In a user management system, you might need to duplicate a list of users for backup or processing purposes. Here’s how you can do it using different methods:

Example Using the addAll() Method

import java.util.ArrayList;
import java.util.List;

class User {
    String name;

    User(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class UserManagement {
    public static void main(String[] args) {
        List<User> sourceList = new ArrayList<>();
        sourceList.add(new User("Alice"));
        sourceList.add(new User("Bob"));
        sourceList.add(new User("Charlie"));

        List<User> targetList = new ArrayList<>();
        targetList.addAll(sourceList);

        System.out.println("Source list: " + sourceList);
        System.out.println("Target list: " + targetList);
    }
}

Output:

Source list: [Alice, Bob, Charlie]
Target list: [Alice, Bob, Charlie]

Conclusion

Copying a list to another list in Java can be done using several methods, including the addAll() method, the Collections.copy() method, the constructor, the Stream API, and a loop. Each method has its advantages and can be chosen based on the specific requirements of your application. Understanding these methods helps you manage and duplicate ArrayList elements efficiently in your Java programs.

Comments

  1. Dear Sir... Thankyou for a good piece of information..
    But just to Correct..
    Won't it be CopyonWriteArrayList

    ReplyDelete
    Replies
    1. Yes we can use CopyonWriteArrayList and this i have already covered in first approach (thread-safe). Cheers!.

      Delete

Post a Comment

Leave Comment