Java Stream distinct() Example

The Java Stream distinct() method is an intermediate operation. 

The Java Stream distinct() method is a non-terminal operation that returns a new Stream that will only contain the distinct elements from the original stream. Any duplicates will be eliminated. 

Java Stream distinct() Example

Here is an example of the Java Stream distinct() method:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args)
    {
        List<String> stringList = new ArrayList<>();

        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        stringList.add("one");

        Stream<String> stream = stringList.stream();

        List<String> distinctStrings = stream
                .distinct()
                .collect(Collectors.toList());

        System.out.println(distinctStrings);
    }
}

Output:

[one, two, three]

Java Stream Methods/APIs Examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments