Languages
[Edit]
EN

Java 8 - remove duplicated elements from List

0 points
Created by:
Tehya-Blanchard
324

In this article, we would like to show you how to remove duplicated elements from List in Java 8.

Quick solution:

List<Integer> numbers = List.of(1, 2, 3, 2, 1);
System.out.println(numbers);  // [1, 2, 3, 2, 1]

List<Integer> distinctNumbers = numbers.stream().distinct().collect(Collectors.toList());
System.out.println(distinctNumbers);  // [1, 2, 3]

 

Practical example

In this example, we use Stream distinct() method to create a new list from the original one without duplicated elements.

import java.util.*;
import java.util.stream.Collectors;

public class Example {

    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 2, 1);
        System.out.println("Original list: " + numbers);    // [1, 2, 3, 2, 1]

        List<Integer> distinctNumbers = numbers.stream().distinct().collect(Collectors.toList());
        System.out.println("Distinct elements: " + distinctNumbers);    // [1, 2, 3]
    }
}

Output:

Original list: [1, 2, 3, 2, 1]
Distinct elements: [1, 2, 3]

References

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join