Pass the condition to be used in the Java8 lambda expression filter () as a parameter

Lambda expressions can be assigned to variables and reused, but their filter conditions are fixed. Assign Java8 lambda expression to variable and reuse it

Therefore, if you want to change the filter condition, you may need to define a separate expression. For example A lambda expression that filters "only strings with a string length of 5", If you want a lambda expression that filters "only strings with a string length of 8", you can define two expressions as follows:

lengthFiveOrEight


//String length 5
final Predicate<String> lengthEqualFive = name -> name.length() == 5;
//String length 8
final Predicate<String> lengthEqualEight = name -> name.length() == 8;

It's okay if the conditions are always fixed, but if the application wants the flexibility to change the conditions, you may have to define as many expressions as there are.

If this condition (5 or 8 in this example) can be received as a parameter, such duplication can be avoided. For example, you can define the following method.

lengthEqualWith


Predicate<String> lengthEqualWith(final Integer expectsLength) {
  return name -> name.length == expectsLength;
}

Instead of simply assigning a lambda expression to a variable, you pass an argument to a method that returns a lambda expression and apply that argument to the lambda expression. By passing expectsLength as a parameter when calling lengthEqualWith (), it is possible to change the conditions flexibly.

Try filtering using the list below.

final List<String> months = 
Arrays.asList("January", "February", "March", "April", "May", "June", "July", "Augast", "September", "October", "November", "December");

LengthEqualWith (N) is applied as follows.

System.out.println("Length is 5");
List<String> result1 = months.stream().filter(lengthEqualWith(5)).collect(Collectors.toList());
result1.forEach(System.out::println);
		
System.out.println("Length is 8");
List<String> result2 = months.stream().filter(lengthEqualWith(8)).collect(Collectors.toList());
result2.forEach(System.out::println);

You will get the following (as expected) results:

Length is 5
March
April
Length is 8
February
November
December

This lambda expression looks for the expectsLength variable in scope, which seems to be called static scope (or syntactic scope). If the expectsLength variable is in scope (cached), the lambda expression uses that value.

In this example, the static scope is inside the lengthEqualWith () method. The expectsLength variable must be final, because lambda expressions can only access local variables in final.

Even if it's not declared final, it seems to work if the condition to be final is met (that is, if the variable is initialized and immutable).

However, Java needs to evaluate whether those conditions are met (it costs money), so caching or not caching these values may make a slight difference in performance. ..

Recommended Posts

Pass the condition to be used in the Java8 lambda expression filter () as a parameter
I want to ForEach an array with a Lambda expression in Java
Source used to get the redirect source URL in Java
Assign a Java8 lambda expression to a variable and reuse it
Create a method to return the tax rate in Java
A Java user over a dozen years ago tried to study the functions of Java8 (Lambda expression).
Pass the i18n locale to JavaScript
Replace with a value according to the match with a Java regular expression
Expression used in the fizz_buzz problem
Determine if the strings to be compared are the same in Java
What is a lambda expression (Java)
The story of forgetting to close a file in Java and failing
How to get the current date as a string in yyyyMMdd format
Reason to add L to the number to be put in Java long type
How to pass a proxy when throwing REST over SSL in Java
How to get the absolute path of a directory running in Java
Set up a Java GUI in a separate thread to keep the main
How to implement Kalman filter in Java
Java reference to understand in the figure
Now let's recap the Java lambda expression
Java SE8 Silver ~ The Road to Pass ~
How to get the date in java
Summarize the life cycle of Java objects to be aware of in Android development
Transform from a normal class to a lambda expression
Two ways to start a thread in Java + @
A story about the JDK in the Java 11 era
How to display a web page in Java
CORBA seems to be removed in Java SE 11. .. ..
Measure the size of a folder in Java
Code to escape a JSON string in Java
Try to create a bulletin board in Java
There seems to be no else-if in java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
[Java] When putting a character string in the case of a switch statement, it is necessary to make it a constant expression
How to use Java API with lambda expression
Java8 to start now ~ forEach and lambda expression ~
How to solve an Expression Problem in Java
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
[Java] Something is displayed as "-0.0" in the output
How to save a file with the specified extension under the directory specified in Java to the list
A study method for inexperienced people to pass Java SE 8 Silver in one month
Pass arguments to the method and receive the result of the operation as a return value
[Java] Lambda expression
Java lambda expression
[Java] Let's declare variables used in the loop in the loop [Variables in the block]
How to create a Java environment in just 3 seconds
[Java] How to omit the private constructor in Lombok
How to run the SpringBoot app as a service
Write ABNF in Java and pass the email address
I tried to organize the cases used in programming
Write a class that can be ordered in Java
I tried to create a Clova skill in Java
How to create a data URI (base64) in Java
A note for Initializing Fields in the Java tutorial
I tried to make a login function in Java
Java classes and instances to understand in the figure
Spring-Boot-2.3 requires javax.validation to be added as a dependency
How to convert A to a and a to A using AND and OR in Java
How to convert a file to a byte array in Java
Try to solve a restricted FizzBuzz problem in Java
Be able to write Hamcrest Matchers in lambda expressions