Java functional programming (6) Search Elements

Source: Internet
Author: User



 

Search Element

Now we are no stranger to the method of transforming the set elegantly designed, but it is powerless to search for elements. However, the filter method is generated for this.

Now we need to retrieve the names starting with N from a name list. Of course, either of them does not exist, and the result may be an empty set. We will first implement it using the old method.

final List
 
   startsWithN = new ArrayList
  
   ();for(String name : friends) {if(name.startsWith(N)) {startsWithN.add(name);}}
  
 


It is enough to write so much code for such a simple event. We first create a variable, and then initialize it as an empty set. Then, traverse the original set to find names starting with a specified letter. If it is found, it is inserted into the set.

We use the filter method to reconstruct the above Code to see how powerful it is.

final List
 
   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 returns true, the element in the running context is added to the result set. If not, skip it. The final return is a Steam, which only contains elements whose expressions return true. Finally, we use a collect method to convert this set into a list. In the next 52 pages of the collect method and the Collecters class, we will further explore this method.

Let's print the elements in this result set:
System.out.println(String.format(Found %d names, startsWithN.size()));


From the output results, we can see that this method finds all matching elements in the set.

Found 2 names


The filter method is the same as the map method, and an iterator is returned, but they are the same. The size of the Set returned by the map is the same as that returned by the input set, but the returned by the filter is not easy to say. It returns the size range of the Set, from 0 to the number of elements in the input set. Unlike map, filter returns a subset of the input set.

So far, we have been very satisfied with the simplicity of the Code brought by lambda expressions. However, if you don't pay attention to it, the Code redundancy problem will gradually grow. Next we will discuss this issue.

Lambda expression Reuse

Lambda expressions seem very concise. In fact, code redundancy may easily occur when you are not careful. Redundancy can lead to low code quality and difficult to maintain; if we want to make a change, we have to get rid of several related codes together.

Avoiding redundancy can also help us improve our performance. The relevant code is concentrated in one place, so that we can analyze its performance and then optimize the code to easily improve the Code performance.

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

final List
 
   friends =Arrays.asList(Brian, Nate, Neal, Raju, Sara, Scott);final List
  
    editors =Arrays.asList(Brian, Jackie, John, Mike);final List
   
     comrades =Arrays.asList(Kate, Ken, Nick, Paula, Zach);We want to filter out names that start with a certain letter.
   
  
 



We want to filter out the names starting with a letter. Use the filter method to implement it.

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();


Lambda expressions make the Code look concise, but they bring code redundancy without knowing it. In the above example, if you want to change the lambda expression, we have to change more than one place-this is not acceptable. Fortunately, we can assign lambda expressions to variables and reuse them, just like using 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. It uses the specified lambda expression to generate an implementation of the test method of Predicate. Now we can explicitly let the Java compiler generate this method, instead of generating the method where the parameter is defined. In the above example, we can explicitly store the lambda expression in a Predicate type reference, and then pass this reference to the filter method; this can easily avoid code redundancy.

Let's refactor the previous Code to make it conform to the DRY principle. (Don't Repeat Yoursef -- DRY -- principle, see The Pragmatic Programmer: From Journeyman to Master [HT00],A book ).

final Predicate
 
   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 need to repeat that lambda expression. We only write it once and store it in a reference of the Predicate type named startsWithN. In the next three filter calls, the Java compiler can see the lambda expression in the Predicate disguise. the Java compiler smiled and silently received it.

This newly introduced variable eliminates code redundancy. However, unfortunately, we will see later that the enemy will soon return to hate, and we will see what more powerful weapons can destroy them for us.


It is not yet resumed. Follow the Java translation site for subsequent articles.


Original article reprinted please indicate the source: http://it.deepinmind.com






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.