#
distinct() method
This tutorial explains how we can use distinct()
method for Streams in Java.
distinct()
method creates a stream without duplicates.
Please take a look at the following example and read carefully the comments. The code is self-explanatory.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
From the base application downloaded from Spring Initializr, I updated the main class as below:
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutionException;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);
List<List<String>> wordsList = Arrays.asList(
Arrays.asList("Laptop", "BMW", "Laptop"),
Arrays.asList("John", "Dan Brown"),
Arrays.asList("computer", "project"));
wordsList.stream()
// Stream<List<String>> will be converted to Stream<String>
.flatMap(Collection::stream)
// the elements are ordered in ASC mode
.sorted()
// the duplicates are removed
.distinct()
.forEach(p -> System.out.println(p));
System.out.println("---------------------------");
}
}
When I run this code I receive:
BMW
Dan Brown
John
Laptop
computer
project
---------------------------
Process finished with exit code 0
When we are working with Streams, we can have:
- INTERMEDIATE operations:
filter
,map
,limit
,sorted
,peak
,distinct
,skip
,flatMap
- TERMINAL operations:
forEach
,count
,sum
,min
,collect
,reduce
,anyMatch
,noneMatch
,allMatch