Java Functional Programming (III): Conversion of lists _java

Source: Internet
Author: User
Tags instance method new set

Conversion of lists

Converting a collection into a new set is as simple as traversing it. Let's say we want to convert the names in the list to uppercase. Let's see what we can achieve.

The string in Java is immutable, so it cannot be changed. We can generate new strings to replace the elements in the list. In this case, however, the original list is gone; there is a problem, the original list may also be immutable, such as Arrays.aslist () generated, so it is not possible to modify the original list. Another drawback is that it is difficult to do parallel operations.

Generating a new fully capitalized list is a good choice.

At first blush this suggestion is weak; performance is a problem that we all pay close attention to. Surprisingly, functional programming is usually more efficient than imperative, and we'll talk about it in 153-page performance issues.

Let's start by using this set to generate a new collection of uppercase letters.

Copy Code code as follows:

Final list<string> uppercasenames = new arraylist<string> ();
for (String name:friends) {
Uppercasenames.add (Name.touppercase ());
}

In imperative code, we first create an empty list and then fill in the name of the uppercase, inserting one at a time while traversing the original list. In order to improve the functional version, the first step is to consider replacing the for loop with the internal iterator foreach mentioned in the 19 page traversal list, as shown in the following example.
Copy Code code as follows:

Final list<string> uppercasenames = new arraylist<string> ();
Friends.foreach (name-> uppercasenames.add (Name.touppercase ()));
System.out.println (Uppercasenames);

We used an internal iterator, but we had to create a new list and then insert the elements into it. We can also make further improvements.

Using lambda expressions

In a newly introduced stream interface, there is a map method that can help us stay away from variability and make the code look more concise. Steam is a bit like a collection iterator, and it also provides the function of a stream function (fluent functions). Using this interface method, we can combine a series of calls so that the code reads like the order of the problem, and the readability is stronger.

The steam map method can be used to convert an input sequence into a sequence of outputs--which matches the work we do.

Copy Code code as follows:

Friends.stream ()
. Map (name-> name.touppercase ())
. ForEach (Name-> System.out.print (name + ""));
System.out.println ();

All the collections in JDK8 support this stream method, which encapsulates the collection into a steam instance. The map method invokes the specified lambda expression or code block for each element in the stream. The map method is very different from the Foreach method, and foreach simply executes the specified function on the elements in the collection. The map method, which combines the results of the lambda expression, returns a result set. Finally we printed all the elements in a foreach method.

The names in the new collection are all capitalized:

Copy Code code as follows:

BRIAN NATE NEAL RAJU SARA SCOTT

The map method is ideal for converting an input set into a new output set. This method ensures that the number of elements in the input and output sequence is the same. However, the type of the input element and the output element can be different. In this example, we both input and output a collection of strings. We can pass the map method to a piece of code that returns, for example, the number of characters contained in the name. In this case, the input is a sequence of strings, but the output is a sequence of numbers, like the following.

Copy Code code as follows:

Friends.stream ()
. Map (name-> name.length ())
. ForEach (Count-> System.out.print (count + ""));

The result is the number of letters in each name:
Copy Code code as follows:

5 4 4 4 4 5

The following version of the lambda expression was used to avoid an explicit modification, so the code is very concise. This is no longer necessary to initialize the empty set and the garbage variable, and this variable is quietly hiding in the bottom of the implementation.

Using method references

We can also use the method reference to make it more concise. Where the implementation of a functional interface needs to be passed in, the Java compiler can accept a lambda expression or a method reference. With this feature, you can replace the name-> name.touppercase () with string::touppercase, just like this:

Copy Code code as follows:

Friends.stream ()
. Map (String::touppercase)
. ForEach (Name-> System.out.println (name));

When the arguments are passed into this generated method-the implementation of the abstract method of the functional interface-Java will invoke the toUpperCase method of the string parameter. This parameter reference is hidden here. Like the previous simple scenario, we could replace the lambda expression with a method reference, and more to see when the 26 page should use the method reference.

Copy Code code as follows:

The small partner asks:
When should I use a method reference?

When using Java programming, we usually use lambda expressions more often than method references. But that doesn't mean that the method reference is not important or useful. When a lambda expression is very brief, it is a good alternative, and it invokes either the instance method or the static method directly. That is, if the lambda expression simply passes a parameter to the method call, we should use the method reference instead.
A lambda expression like this, a bit like Tom Smykowski in a movie work bug, its job is to "take the demand from the customer to the software engineer". Because of this, I refer to this type of refactoring method as a mode of work.
In addition to simplicity, the use of method references, the meaning and function of the method name itself can be better reflected.
The compiler plays a key role behind the use of method references. The object and parameters referenced by the method are deduced from the arguments that are passed in the generated method. This allows you to write code that is simpler than using a lambda expression using a method reference. However, if the parameter is to be modified before it is passed to the method or the result of the call is returned, we will not be able to use the convenient wording.

In the previous example, a method reference is a reference to an instance method. A method reference can also refer to a static method and the method that accepts the argument. We'll see an example of this later.

Lambda expressions help us to traverse the collection and to transform the set. As we'll see here, it also helps us quickly pick an element from the collection.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.