Learn how to remove duplicates from LinkedList in Java using Java 8 Stream API and distinct() method with examples. LinkedList is one of the most commonly used collection classes in Java. Sometimes a LinkedList may contain duplicate elements that need to be removed before further processing.
Code Explanation (Step-by-Step)
- Convert the array elements into a List using the Arrays.asList() method.
- Create a LinkedList object and pass the list to its constructor.
- Convert the LinkedList into a stream using the stream() method.
- Use the distinct() method to remove duplicate elements from the stream .
- Use Collectors.toList() to collect the unique elements into a new list.
- Print the list containing the unique elements.
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveDuplicates {
public static void main(String[] args) {
List list = Arrays.asList(1, 2, 3, 5, 6, 1, 2, 3);
LinkedList linkedList = new LinkedList<>(list);
List number = linkedList.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Number List: " + number);
}
}
Output :-
Number List :- [1, 2, 3, 5, 6]
How distinct() Method Works
The distinct() method is a convenient way to remove duplicate elements from a stream. It processes each element, keeps only the first occurrence, and returns a stream containing unique values while preserving the original order.
Syntax : stream.distinct()
Can distinct() be used with parallel streams?
distinct() method can be used with parallel streams. it will remove duplicate elements across multiple threads. Since distinct() is a stateful intermediate operation, maintaining uniqueness and encounter order can reduce some of the performance benefits of parallel processing.
import java.util.Arrays;
import java.util.List;
public class DistinctParallelStream {
public static void main(String[] args) {
List numbers = Arrays.asList(1, 2, 3, 2, 4, 1, 5, 3);
numbers.parallelStream()
.distinct()
.forEach(System.out::println);
}
}
Here are some Java-related programs that will help you understand Java concepts better: