Using lexical scopes and closures
Many developers have this misconception that using lambda expressions can result in code redundancy and lower code quality. On the contrary, even if the code becomes more complex, we will not compromise the code quality for the simplicity of the code, as we will see below.
We can reuse lambda expressions in the previous example, but if you match another letter, the problem of code redundancy quickly returns. Let's take a closer look at the problem and then use the lexical scope and the closure to solve it.
The redundancy caused by lambda expressions
Let's filter out the letters that start with N or b from the friends. Continuing with the example above, the code we write might be like this:
Copy Code code as follows:
Final predicate<string> startswithn = name-> name.startswith ("N");
Final predicate<string> STARTSWITHB = name-> name.startswith ("B");
Final long Countfriendsstartn =
Friends.stream ()
. Filter (STARTSWITHN). Count ();
Final long COUNTFRIENDSSTARTB =
Friends.stream ()
. Filter (STARTSWITHB). Count ();
The first predicate to determine whether the name begins with N, and the second is to decide whether to start with B. We pass these two instances to the two filter method invocation, respectively. This looks reasonable, but two predicate produce redundancy, and they are just different letters from the check. Let's look at how we can avoid this redundancy.
Use lexical scopes to avoid redundancy
In the first scenario, we can extract the letters as arguments to the function and pass the function to the filter method. This is a good method, but filter is not accepted by any function. It only accepts a function with only one parameter, which corresponds to the element in the collection, returns a Boolean value, and it expects a predicate to pass in.
We want to have a place where we can cache the letter until the parameter is passed (here is the parameter name). Here's a new function like this.
Copy Code code as follows:
public static predicate<string> Checkifstartswith (final String letter) {
Return name-> name.startswith (letter);
}
We define a static function Checkifstartswith, which receives a string parameter and returns a predicate object that can just be passed to the filter method for later use. Unlike the higher-order functions seen earlier, this method returns a function as a function argument. But it's also a higher order function, which we've already mentioned in 12-page evolution, not change.
The predicate object returned by the Checkifstartswith method is somewhat different from the other lambda expressions. In the return name-> Name.startswith (letter) statement, we know exactly what name is, and it is the argument passed into the lambda expression. But what exactly is a variable letter? It is on the outside of the anonymous function, and Java finds the domain that defines the lambda expression, and finds this variable letter. This is called the lexical scope. The lexical scope is a useful thing that allows us to cache a variable in a used domain for later use in another context. Because this lambda expression uses variables in its domain of definition, this is also known as closures. For the access restrictions on lexical scopes, can you see the limitations of the lexical scope of the 31 pages?
What are the limitations of the lexical scope?
In a lambda expression, we can only access the final type in its domain or actually the final type of a local variable.
A lambda expression may be invoked immediately, or it may delay the call, or initiate a call from a different thread. To avoid competition, local variables in the domain we are accessing are not allowed to be modified once initialized. Any modification will result in a compilation exception.
This is resolved after the final mark, but Java does not force us to be so marked. In fact, Java is looking at two points. The variable that is accessed must be initialized in the method in which it is defined, and before the lambda expression is defined. Second, the values of these variables cannot be modified-that is, they are in fact final types, although they are not so marked.
A stateless lambda expression is a Run-time constant, whereas a lambda expression that uses a local variable has an additional computational overhead.
When the filter method is invoked we can use the lambda expression returned by the Checkifstartswith method, like this:
Copy Code code as follows:
Final long Countfriendsstartn =
Friends.stream (). Filter (Checkifstartswith ("N")). Count ();
Final Long COUNTFRIENDSSTARTB = Friends.stream ()
. Filter (Checkifstartswith ("B")). Count ();
Before we call the filter method, we first call the Checkifstartswith () method, and we take the desired letters in. This call soon returns a lambda expression, and then we pass it to the filter method.
By creating a higher-order function (here is Checkifstartswith) and using the lexical scope, we successfully removed the redundancy in the code. We don't have to repeat the decision that name is beginning with a certain letter.
Refactoring, narrowing scopes
In the previous example we used a static method, but we didn't want to use the static method to cache the variable, which would confuse our code. It's best to narrow the scope of the function to where it is used. We can use a function interface to implement this.
Copy Code code as follows:
Final function<string, predicate<string>> startswithletter = (String letter)-> {
Predicate<string> checkstarts = (String name)-> Name.startswith (letter);
return checkstarts; };
This lambda expression replaces the original static method, which can be put into a function and defined before it needs to be used. The startwithletter variable refers to a string in which the argument is a predicate function.
This is a much simpler version than using the static method, but we can still refactor it to make it a little more concise. From a practical point of view, this function is the same as the previous static method; they all receive a string to return a predicate. To not explicitly declare a predicate, we replace it with a LAMDBA expression.
Copy Code code as follows:
Final function<string, predicate<string>> startswithletter = (string letter)-> (string name)-> Tartswith (letter);
We got rid of the mess, but we can also get rid of the type declaration and make it a little more concise, and the Java compiler does the type derivation based on the context. Let's look at the improved version.
Copy Code code as follows:
Final function<string, predicate<string>> startswithletter =
Letter-> name-> name.startswith (letter);
It takes a little time to get used to this simple grammar. If it blinds your eyes, look at the other place first. We've completed the refactoring of the code, and now we can replace the original Checkifstartswith () method with it, like this:
Copy Code code as follows:
Final Long Countfriendsstartn = Friends.stream ()
. Filter (Startswithletter.apply ("N")). Count ();
Final Long COUNTFRIENDSSTARTB = Friends.stream ()
. Filter (Startswithletter.apply ("B")). Count ();
In this section we use higher order functions. We see how to create a function in a function, and how to return a function through a function, if the function is passed to another function. These examples show the simplicity and reusability of lambda expressions.
In this section we have fully played the role of function and predicate, but let's look at what the difference is between the two of them. predicate accepts a parameter of type T, returns a Boolean value to represent the true and false of its corresponding judgment condition. When we need to make a conditional judgment, we can use Predicateg to do it. Methods such as filter for filtering elements receive predicate as parameters. and Funciton represents a function whose argument is a variable of type T and returns a result of the R type. It is more generic than predicate that can only return a Boolean. As long as the input is converted to an output, we can use function, so it is reasonable for map to use function as a parameter.
As you can see, selecting elements from the collection is very simple. Below we'll show you how to select only one element from the collection.