rashmi agar
69 posts
Mar 17, 2025
10:19 PM
|
I've been working with Java ArrayList and recently ran into an issue where my list contains duplicate elements. java arraylist remove duplicates while maintaining the original order of elements. I’ve done some research and found multiple approaches, but I’m unsure which one is the best in terms of performance and readability.
Methods I’ve Considered: Using a LinkedHashSet
Since LinkedHashSet maintains insertion order and doesn’t allow duplicates, this seems like a simple and effective solution. Example: java Copy Edit import java.util.*;
public class RemoveDuplicates { public static void main(String[] args) { ArrayList list = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange", "banana")); LinkedHashSet set = new LinkedHashSet<>(list); ArrayList uniqueList = new ArrayList<>(set); System.out.println(uniqueList); } } Pros: Easy to implement, maintains order. Cons: Requires extra memory for LinkedHashSet. Using a Loop and a Temporary List
Iterating over the list and adding elements to a new list only if they’re not already present. Example: java Copy Edit import java.util.*;
public class RemoveDuplicates { public static void main(String[] args) { ArrayList list = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange", "banana")); ArrayList uniqueList = new ArrayList<>(); for (String item : list) { if (!uniqueList.contains(item)) { uniqueList.add(item); } } System.out.println(uniqueList); } } Pros: Simple, no external data structures needed. Cons: contains() method runs in O(n), leading to O(n²) complexity. Using Java 8 Streams
Java 8 introduced distinct() in Streams, which can remove duplicates concisely. Example: java Copy Edit import java.util.*; import java.util.stream.Collectors;
public class RemoveDuplicates { public static void main(String[] args) { ArrayList list = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange", "banana")); List uniqueList = list.stream().distinct().collect(Collectors.toList()); System.out.println(uniqueList); } } Pros: Concise and efficient. Cons: May not be the fastest for large lists. Which Method is Best? Each method has its trade-offs. If memory usage isn’t a concern, LinkedHashSet is a great option. If you’re using Java 8 or later, Streams provide a clean and readable approach. The manual loop works but isn’t the most efficient.
|