EN
Java 8 - remove duplicated elements from List
0 points
In this article, we would like to show you how to remove duplicated elements from List in Java 8.
Quick solution:
xxxxxxxxxx
1
List<Integer> numbers = List.of(1, 2, 3, 2, 1);
2
System.out.println(numbers); // [1, 2, 3, 2, 1]
3
4
List<Integer> distinctNumbers = numbers.stream().distinct().collect(Collectors.toList());
5
System.out.println(distinctNumbers); // [1, 2, 3]
In this example, we use Stream distinct()
method to create a new list from the original one without duplicated elements.
xxxxxxxxxx
1
import java.util.*;
2
import java.util.stream.Collectors;
3
4
public class Example {
5
6
public static void main(String[] args) {
7
List<Integer> numbers = List.of(1, 2, 3, 2, 1);
8
System.out.println("Original list: " + numbers); // [1, 2, 3, 2, 1]
9
10
List<Integer> distinctNumbers = numbers.stream().distinct().collect(Collectors.toList());
11
System.out.println("Distinct elements: " + distinctNumbers); // [1, 2, 3]
12
}
13
}
Output:
xxxxxxxxxx
1
Original list: [1, 2, 3, 2, 1]
2
Distinct elements: [1, 2, 3]