Skip to main content
TopMiniSite

Back to all posts

How to Remove Duplicates In A Java List?

Published on
4 min read

Table of Contents

Show more
How to Remove Duplicates In A Java List? image

To remove duplicates in a Java list, you can follow the steps below:

  1. Create a new instance of a Set, which does not allow duplicate elements. You can use the HashSet implementation, which does not preserve the order of elements, or LinkedHashSet, which preserves the insertion order.
  2. Iterate over the Java list and add each element to the Set. The Set will automatically remove any duplicates.
  3. Create a new ArrayList or LinkedList to store the unique elements in the desired order.
  4. Iterate over the Set and add each element to the new list.

Here's an example code snippet that demonstrates these steps:

import java.util.*;

public class RemoveDuplicates { public static void main(String[] args) { List listWithDuplicates = Arrays.asList(1, 2, 3, 4, 2, 3, 5, 1, 6);

    Set<Integer> set = new LinkedHashSet<>(); // Preserves insertion order
    set.addAll(listWithDuplicates);

    List<Integer> listWithoutDuplicates = new ArrayList<>(set);

    System.out.println("List with duplicates: " + listWithDuplicates);
    System.out.println("List without duplicates: " + listWithoutDuplicates);
}

}

In this example, the original list listWithDuplicates contains duplicate elements. We create a LinkedHashSet set and add all elements from the list to it. Since a set cannot have duplicate entries, it automatically removes the duplicates. Finally, we create a new listWithoutDuplicates from the unique elements in the set and print both lists for comparison.

Output:

List with duplicates: [1, 2, 3, 4, 2, 3, 5, 1, 6] List without duplicates: [1, 2, 3, 4, 5, 6]

Using this approach, you can effectively remove duplicates from a Java list while preserving the order of the unique elements.

How do you convert an array to a list in Java?

In Java, you can convert an array to a list using the Arrays.asList() method. Here is an example:

import java.util.Arrays; import java.util.List;

public class Main { public static void main(String[] args) { // Create an array Integer[] array = {1, 2, 3, 4, 5};

    // Convert the array to a list
    List<Integer> list = Arrays.asList(array);

    // Print the list
    System.out.println(list);
}

}

Output:

[1, 2, 3, 4, 5]

Note that the resulting list is a fixed-size list backed by the original array, which means you cannot add or remove elements from the list. If you need a mutable list, you can create a new ArrayList and pass the array to its constructor like this:

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

public class Main { public static void main(String[] args) { // Create an array Integer[] array = {1, 2, 3, 4, 5};

    // Convert the array to a mutable list
    List<Integer> list = new ArrayList<>(Arrays.asList(array));

    // Add an element to the list
    list.add(6);

    // Print the list
    System.out.println(list);
}

}

Output:

[1, 2, 3, 4, 5, 6]

How would you remove duplicates in a list without using any additional data structure?

One way to remove duplicates in a list without using additional data structure is to iterate through the list and remove any element that has already been encountered.

Here is an example code in Python:

def remove_duplicates(lst): if len(lst) == 0: return lst

# Start from the first element current_index = 0

while current_index < len(lst) - 1: current_element = lst[current_index] next_index = current_index + 1

# Iterate through the list to compare with current element
while next\_index < len(lst):
    if lst\[next\_index\] == current\_element:
        # Remove the duplicate element
        lst.pop(next\_index)
    else:
        next\_index += 1

current\_index += 1

return lst

Example usage

my_list = [1, 2, 3, 3, 4, 4, 5] print(remove_duplicates(my_list))

Output: [1, 2, 3, 4, 5]

Note that this approach has a time complexity of O(n^2), where n is the length of the list. It is not the most efficient method for removing duplicates, but it satisfies the condition of not using any additional data structure.

How do you remove duplicates from a Java list without changing the original list?

To remove duplicates from a Java list without changing the original list, you can create a new list and iterate over the original list, adding only unique elements to the new list. Here's an example implementation:

import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set;

public class Main { public static void main(String[] args) { List originalList = new ArrayList<>(); originalList.add(1); originalList.add(2); originalList.add(3); originalList.add(2); originalList.add(4); originalList.add(3);

    List<Integer> uniqueList = removeDuplicates(originalList);

    System.out.println("Original List: " + originalList);
    System.out.println("Unique List: " + uniqueList);
}

public static <T> List<T> removeDuplicates(List<T> list) {
    Set<T> set = new LinkedHashSet<>(list); // Use LinkedHashSet to maintain order
    return new ArrayList<>(set);
}

}

Output:

Original List: [1, 2, 3, 2, 4, 3] Unique List: [1, 2, 3, 4]

In the removeDuplicates method, we create a new LinkedHashSet and pass the original list as the argument. A LinkedHashSet stores unique elements in the order they were inserted. We then convert the set back to a list using new ArrayList<>(set), ensuring the order is preserved.