Java Functional Programming (vi): Optional_java

Source: Internet
Author: User

Select a single element

Intuitively, selecting a single element is certainly a lot simpler than selecting multiple, but there are some problems. Let's look at what the general practice is, and then see how to solve it with a lambda expression.

Let's start by creating a new method to find an element that starts with a specific letter and then prints it out.

Copy Code code as follows:

public static void Pickname (
Final list<string> names, final String startingletter) {
String foundname = null;
for (String name:names) {
if (Name.startswith (Startingletter)) {
Foundname = name;
Break
}
}

This method is just as stink as the old garbage truck. We first created a foundname variable and then initialized it to null--, which is the source of the stench. We have to check if it is empty, or we will throw a nullpointerexception or an error response. We also use an external iterator to loop through the list, and if we find what we want, we have to jump out of the loop, which adds to the original stink: the basic type of paranoia, imperative style, variability, all alive. Once we exit the loop, we have to check the results before we can print. So little task to write such a long code.

Let's re-examine the problem. We just want to be able to pick the first matching element and be able to safely handle a situation where there is no such element. Let's rewrite this pickname method with a lambda expression.

Copy Code code as follows:

public static void Pickname (
Final list<string> names, final String startingletter) {
Final optional<string> Foundname =
Names.stream ()
. Filter (name->name.startswith (startingletter))
. FindFirst ();
System.out.println (String.Format ("A name starting with%s:%s"),
Startingletter, Foundname.orelse ("No name Found"));
}

There are some powerful features in the JDK that make this code much simpler. First we use the filter method to obtain all the elements that satisfy the condition, and then use the FindFirst method of the Stream class to select the first element to return the collection. This method returns a optional object, which is the official authentication of the null variable in Java deodorant.

The optional class is very useful, and you don't have to control whether the results are present. It allows us to avoid the exception of empty pointers, and to make it clear that no result is a possible result. The Ispresent () method lets us know if the result is present, and we can use the Get () method if we want to obtain the result value. We can also use (the method name to shock you) OrElse method to set a default value for it, as in the previous code.

We use the friends set we've been using to verify our Pickname method.

Copy Code code as follows:

Pickname (Friends, "N");
Pickname (Friends, "Z");

This code selects the first matching element and, if not, prints out a friendly hint.
Copy Code code as follows:

A name starting with N:nate
A name starting with Z:no name found

The combination of the FindFirst () method and the Optinal class reduces the amount of code we have, and it looks good. But the optional class features far more than that. For example, in addition to providing a default value when an object does not exist, you can use it to run a piece of code if the result exists, or a lambda expression like this:
Copy Code code as follows:

Foundname.ifpresent (name-> System.out.println ("Hello" + name);

The flow-style elegant functional style looks better with the command-style selection of the first matching name code. But is there a bit too much to do in this version of the call stream (first to select all the matches and return to the first item)? Of course not, these methods are very intelligent and they can work on demand (we'll delve into this in the lazy evaluation of the next 113-page stream).

The example of selecting a single element shows the more powerful features of the JDK library, so let's look at how the lambda expression is based on a collection to find the desired value.

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.