Java Stream Filter
Stream.filter() is a method in Java we use while working with streams. It traverses through all the elements present and removes or filters out all those elements that are not matching with the specified condition through a significant argument. This is basically an operation that takes place in between the stream interface. The function returns an output stream having the elements of the input stream matching the given conditions.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
The argument passed with the filter() will be a stateless predicate and applies to each and every element to identify if it should be included or not. We can pass lambda expression also through this since the predicate falls under the functional interface category. The output contains a new stream that can be used for any other operations relevant to any stream.
Syntax:
Stream<T> filter(Predicate<? super T> condition)d
Predicate represents a functional interface and shows the condition we use to filter out elements that do not match the stream.
Examples to Implement Java Stream Filter
Let us undertake a few of examples to understand the functionality of the Java stream() function.
Example #1
Code:
import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<Integer> arr = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18, 19, 20); arr.stream() .filter(i -> i % 3 == 0) .forEach(System.out::println); } }
Output:
Explanation: This is a very basic and simple example that shows how to use the java stream filter function. In this example, we are declaring an array of random numbers and assigning them to a List. Then we are using the stream filter to filter out all those elements in the given array that satisfy the condition given, i.e. all the numbers in the array that gives a modulus of 3 as 0 are filtered and displayed in the output.
Example #2
Code:
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class Main { public static void main(String[] args) { List<Integer> arr = Arrays.asList(21, 22, 23, 24, 25, 26, 27, 28, 29, 30); Predicate<Integer> condition = new Predicate<Integer>() { @Override public boolean test(Integer i) { if (i % 4 == 0) { return true; } return false; } }; arr.stream().filter(condition).forEach(System.out::println); } }
Output:
Explanation: In this example, we are first declaring an input array consisting of a random set of numbers and assigning them a list. Here we are also showing how to use and declare predicate along with stream filter function by first creating an object of the same of the name condition. Then a class of the name test having an input parameter of integer I am created where we are checking the modulus of 4 of the given array. This function returns a boolean value of true if modulues of 4 return 0 and false otherwise. By taking this return value, the stream function is then used to fetch the elements from the array whose condition is true.
Example #3
Code:
import java.util.*; public class Example { public static void main(String[] args) { //Array creation List<String> arr1 = Arrays.asList("trial", "simple", "node"); //Calling usingFiltOutput function List<String> op = usingFiltOutput(arr1, "node"); //for loop to print array for (String arr : op) { System.out.print(arr); System.out.print("\n"); } } private static List<String> usingFiltOutput(List<String> arr2, String filter) { List<String> op = new ArrayList<>(); for (String arr1 : arr2) { if (!"node".equals(arr1)) { op.add(arr1); } } return op; } }
Output:
Explanation: In the above example, we are showing the filtering of array elements where we are filtering the element “node” by using the stream filter method
Example #4
Code:
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Car> listCar = new ArrayList<>(); listCar.add(new Car("Maruti", 350000)); listCar.add(new Car("Toyota", 400000)); listCar.add(new Car("Mahindra", 500000)); listCar.add(new Car("Honda", 600000)); // displaying all cars with cost more than 4lakh listCar.stream().filter(c -> (c.getID() > 400000)) .forEach(c -> System.out.println(c.getCompany())); } } class Car { private String company; private int ID; public Car() { } public Car(String n, int a) { this.company = n; this.ID = a; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } }
Output:
Explanation: In this example, we shall see a kind of a real-time application where the list of different companies of cars and their basic cost has been assigned to an array list as shown. Then we are defining a few methods below to fetch the individual values from the array list. getcost method is used to get the cost of that particular car, and getCompany is used to get the company name from the input array list. Then in the main function, we are using the Java stream filter function to fetch only those car company names whose approximate cost falls above Rs.400000.
Example #5
Code:
import java.util.*; import java.util.stream.Collectors; class Example{ int pro_id; String pro_name; float pro_cost; public Example(int pro_id, String pro_name, float pro_cost) { this.pro_id = pro_id; this.pro_name = pro_name; this.pro_cost = pro_cost; } } public class JavaStreamExample { public static void main(String[] args) { List<Example> productsList = new ArrayList<Example>(); //Here we are listing the products productsList.add(new Example(1,"Shirt",1500f)); productsList.add(new Example(2,"Long Sleeve Top",1000f)); productsList.add(new Example(3,"Crop Top",1600f)); productsList.add(new Example(4,"Jeans",2100f)); productsList.add(new Example(5,"Skirt",1800f)); List<Float> pricesList = productsList.stream() .filter(p ->p.pro_cost> 1500) .map(pm ->pm.pro_cost) .collect(Collectors.toList()); System.out.println(pricesList); } }
Output:
Explanation: In this example, we are first declaring out a few parameters regarding the products of a dress shop, such as product id, name, and cost. And by using the ArrayList, we are adding certain products into it along with its parameters. In the end, by using the java stream filter, we are filtering out a few products whose cost is above Rs.1500. This shows a real-time application of this method.
Conclusion
We saw all the different kinds of combinations with which the Java stream filter can be used to filter out certain elements in the array based on the condition we give. It can also be combined with Java streams, array lists, collections, and many others based on the requirement.
The above is the detailed content of Java Stream Filter. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
