Java Functional Programming (IV): Finding an element in a collection _java

Source: Internet
Author: User

Find elements

Now we are no stranger to the elegant method of transforming the collection, but it is powerless to find elements. But the filter method was born for this.

Now we're going to take the names that start with n from a list of names. Of course, there may not be one, and the result may be an empty collection. Let's start with the old method.

Copy Code code as follows:

Final list<string> startswithn = new arraylist<string> ();
for (String name:friends) {
if (Name.startswith ("N")) {
Startswithn.add (name);
}
}

Such a simple event, write so much code, also enough long-winded. We first create a variable and then initialize it as an empty collection. The original collection is then traversed to find names that begin with the specified letter. If found, it is inserted into the collection.

We use the filter method to refactor the above code to see how powerful it is.

Copy Code code as follows:

Final list<string> startswithn =
Friends.stream ()
. Filter (Name-> name.startswith ("N"))
. Collect (Collectors.tolist ());

The filter method receives a lambda expression that returns a Boolean value. If the expression evaluates to True, the element in the run context is added to the result set, and if it is not, skip it. The final return is a steam, which contains only those elements whose expressions return true. Finally, we use a Collect method to convert this set into a list--in the next 52 pages using the Collect method and the Collecters class, we'll go into a more in-depth discussion of this approach.

Let's print out the elements in this result set:

Copy Code code as follows:

System.out.println (String.Format ("Found%d Names", Startswithn.size ()));

It is obvious from the output that this method finds all the matching elements in the set.
Copy Code code as follows:

Found 2 Names

The filter method, like the map method, also returns an iterator, but they are just the same. The collection returned by the map is the same size as the input collection, and the filter returns a bad word. It returns the size range of the collection, from 01 to the number of elements in the input set. Unlike the map, filter returns a subset of the input set.

So far, the code simplicity of lambda expressions is satisfying, but if you don't pay attention, the problem of code redundancy begins to grow. Let's discuss the problem below.

Reuse of lambda expressions

The lambda expression looks neat, and it's easy to inadvertently get code redundancy. Redundancy can lead to poor code quality and maintenance; If we want to make a change, we have to get rid of several relevant code together.

Avoiding redundancy can also help us improve performance. The related code is concentrated in one place so that we can analyze its performance and then optimize the code so that it is easy to improve the performance of the code.

Now let's take a look at why using lambda expressions can easily lead to code redundancy, and consider how to avoid it.

Copy Code code as follows:

Final list<string> friends =
Arrays.aslist ("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");
Final list<string> editors =
Arrays.aslist ("Brian", "Jackie", "John", "Mike");
Final list<string> comrades =
Arrays.aslist ("Kate", "Ken", "Nick", "Paula", "Zach");
We want to "filter out names" "Start with" a certain letter.

We want to filter the name of the beginning of a certain letter. First use the filter method to achieve a simple.
Copy Code code as follows:

Final long Countfriendsstartn =
Friends.stream ()
. Filter (Name-> name.startswith ("N")). Count ();
Final long Counteditorsstartn =
Editors.stream ()
. Filter (Name-> name.startswith ("N")). Count ();
Final long Countcomradesstartn =
Comrades.stream ()
. Filter (Name-> name.startswith ("N")). Count ();

A lambda expression makes the code look neat, but it unknowingly brings in the redundancy of the code. In the example above, if you want to change the lambda expression, we have to change more than one place--that's not going to work. Fortunately, we can assign lambda expressions to variables, and then reuse them, just as we do with objects.

The filter method, the receiver of the lambda expression, receives a reference to a Java.util.function.Predicate function interface. Here, the Java compiler comes in handy, using a specified lambda expression to generate an implementation of the predicate test method. Now we can make it more explicit for the Java compiler to generate this method, rather than reproducing it in the location where the parameter is defined. In the example above, we can explicitly store a lambda expression in a predicate type reference, and then pass the reference to the filter method, which is easy to avoid code redundancy.

Let's refactor the previous code to conform to the dry principle. (Don ' t Repeat yoursef--dry--principle, see the Pragmatic Programmer:from journeyman to master[ht00], a book).

Copy Code code as follows:

Final predicate<string> startswithn = name-> name.startswith ("N");
Final long Countfriendsstartn =
Friends.stream ()
. Filter (STARTSWITHN)
. Count ();
Final long Counteditorsstartn =
Editors.stream ()
. Filter (STARTSWITHN)
. Count ();
Final long Countcomradesstartn =
Comrades.stream ()
. Filter (STARTSWITHN)
. Count ();

Now we don't have to write that lambda expression again, we only write it once and store it in a reference to a predicate type called STARTSWITHN. In the three filter calls that follow, the Java compiler sees the lambda expression in the predicate disguise, laughing and silently accepting it.

This newly introduced variable eliminates code redundancy for us. Unfortunately, we'll see later that the enemy will soon come back for revenge, and we'll see what more powerful weapons can do to destroy them.

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.