# filter() method

In 
Published 2023-06-10

This tutorial explains how we can use distinct() method for Streams in Java.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

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
---------------------------