This series of articles is translated from Venkat SubramaniamFunctional Programming in Java
List Conversion
Converting a set into a new one is as simple as traversing it. Suppose we want to convert the name in the list into uppercase. Let's take a look at the implementation methods.
The string in Java is unchangeable, so it cannot be changed. We can generate a new string to replace the original elements in the list. However, in this case, the original list is gone. Another problem is that the original list may be immutable, such as Arrays. asList () is generated, so you cannot modify the original list. Another drawback is that it is difficult to perform parallel operations.
Generating a new fully capitalized list is a good choice.
At first glance, this suggestion is weak. performance is a problem that we are very concerned about. Surprisingly, functional programming usually has higher performance than imperative programming.Performance problems.
Let's start by using this set to generate a new set of uppercase letters.
final List uppercaseNames = new ArrayList();
for(String name : friends) {
uppercaseNames.add(name.toUpperCase());
}
In the imperative code, we first create an empty list, and then fill in the upper-case name. During the traversal of the original list, insert one at a time. To improve the function version, we can consider 19 pages in the first step.Traverse listThe internal iterator forEach mentioned in replaces the for loop, as shown in the following example.
final List uppercaseNames = new ArrayList();
friends.forEach(name -> uppercaseNames.add(name.toUpperCase()));
System.out.println(uppercaseNames);
We use an internal iterator, but we have to create a new list and then insert the elements into it. We can make further improvements.
Use lambda expressions
There is a map method in a newly introduced Stream interface, which can help us stay away from variability and make the Code look more concise. Steam is a bit like a set iterator, and it also provides the fluent functions function. Using this interface, we can combine a series of calls to make the Code read in the same order as the problem is described and more readable.
The Steam map method can be used to convert an input sequence into an output sequence, which is very consistent with what we need to do.
friends.stream()
.map(name -> name.toUpperCase())
.forEach(name -> System.out.print(name + " "));
System.out.println();
All sets in JDK 8 support this stream method, which encapsulates the set into a Steam instance. The map method calls a specified lambda expression or code block for each element in the Stream. The map method is very different from the forEach method. forEach simply executes the specified function for the elements in the set. The map method collects the running results of lambda expressions and returns a result set. Finally, we use the forEach method to print all the elements.
All the names in the new set are in uppercase:
BRIAN NATE NEAL RAJU SARA SCOTT
The map method is suitable for converting an input set into a new output set. This method ensures that the number of elements in the input/output sequence is the same. However, the types of input and output elements can be different. In this example, both input and output are strings. We can pass a piece of code to the map method to let it return, for example, the number of characters contained in the name. In this case, the input is a string sequence, but the output is a numerical sequence, as shown below.
friends.stream()
.map(name -> name.length())
.forEach(count -> System.out.print(count + " "));
The result is the number of letters in each name:
5 4 4 4 4 5
Using a later version of the lambda expression avoids explicit modification operations. Such code is very concise. In this way, the empty set and the garbage variable do not need to be initialized. The variable is hidden in the underlying implementation.
Reference
We can also use method reference to make it more concise. The Java compiler can accept lambda expressions or method references where you need to pass in the implementation of functional interfaces. With this feature, you can replace name-> name. toUpperCase () with String: toUpperCase, just like this:
friends.stream()
.map(String::toUpperCase)
.forEach(name -> System.out.println(name));
When the parameter is passed in to the generated method-the implementation of the abstract method of the function interface-, Java will call the toUpperCase method of the String parameter. This parameter reference is hidden here. For simple scenarios like above, we can replace lambda expressions with method references. For more information, see the 26-pageWhen should I use method reference?.
In the previous example, a method reference references an instance method. You can also reference a static method and a method that accepts parameters. We will see this example later.
The partner asked:
When should I use method reference?
When using Java programming, we usually use lambda expressions much more than method reference. However, this does not mean that method reference is unimportant or useless. When a lambda expression is very short, it is a good alternative. It directly calls the instance method or static method. That is to say, if the lambda expression only passes a parameter to the method call, we should use the method reference instead.
Lambda expressions like this are a bit like Tom smykoski in movies.A worm at workAs mentioned in, its job is to "give the customer the requirement to the software engineer ". Because of this, I call this re-composition method reference pattern a worm pattern at work.
In addition to being concise, the meanings and functions of method names can be better reflected by using method references.
The compiler plays a key role behind method reference. The target object and parameters referenced by the method are derived from the parameters passed in the generated method. This allows you to use method references to write code that is more concise than using lambda expressions. However, if the parameter is to be modified before it is passed to the method or the call result is to be returned, we will not be able to use this convenient method.
Lambda expressions can help us traverse the set and convert the set. As we will see below, it can also help us quickly select an element from the set.
Not yet resumed. Follow deepinmind in subsequent articles.
Original article reprinted please indicate the source: http://it.deepinmind.com