#
filter() method
This tutorial explains how we can use distinct()
method for Streams in Java.
filter()
method creates a new stream by removing some elements from the input stream.
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;
import java.util.stream.Stream;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);
Integer[] numbers = { 10, 22, 32, 42, 50, 65, 70 };
Stream.of(numbers)
// We are using a simple lambda expression
.filter(x -> x > 25)
.forEach(p -> System.out.println(p));
System.out.println("----------------------------");
Stream.of(numbers)
// We can add more conditions
.filter(x -> x > 25 && x < 50)
.forEach(p -> System.out.println(p));
System.out.println("---------------------------");
Stream.of(numbers)
// // We can add a more complex code
.filter(x -> {
var ret = true;
if (x%5 == 0) {
ret = false;
}
return ret;
})
.forEach(p -> System.out.println(p));
System.out.println("---------------------------");
}
}
When I run this code I receive:
32
42
50
65
70
----------------------------
32
42
---------------------------
22
32
42
---------------------------
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
collect() operation works with groupingBy and partitioningBy options.
- groupingBy : the result generally is a Map with more records.
- partitioningBy : the result generally is a Map with 2 records, where the possible keys are "true" and "false".