Java 8: compose and andThen combination Functions

Source: Internet
Author: User

Java 8: compose and andThen combination Functions

In this article, I will discuss the combination of the two compose and andThen functions provided by the Function interface.

What is a function combination?

First, you need to create some small reusable functions, and then combine these small functions into new functions.

Now, how can we use the compose and andThen methods to complete the combination of functions?

First, define two simple functions: times2 and squared.

 
  1. Function<Integer, Integer> times2 = e -> e * 2; 
  2. Function<Integer, Integer> squared = e -> e * e; 

Next, use compose and andThen to connect them.

 
  1. times2.compose(squared).apply(4);  
  2. // Returns 32 
  3. times2.andThen(squared).apply(4);  
  4. // Returns 64 

As you can see, the difference between compose and andThen is that the order of function execution is different. The compose function executes the parameters first and then the caller, while andThen executes the caller first and then the parameters.

Let's start to combine functions.

We will first create an example to demonstrate how to use this method to create reusable small code snippets-and then combine these code snippets in different ways.

Consider the following questions.

There is a list of articles, which need to be filtered according to different requirements.

First, we will introduce two basic functions-byAuthor and byTag-to filter articles based on authors and tags.

 
  1. BiFunction<String, List<Article>, List<Article>> byAuthor = 
  2.     (name, articles) -> articles.stream() 
  3.         .filter(a -> a.getAuthor().equals(name)) 
  4.         .collect(Collectors.toList()); 
  5. BiFunction<String, List<Article>, List<Article>> byTag =  
  6.     (tag, articles) -> articles.stream() 
  7.         .filter(a -> a.getTags().contains(tag)) 
  8.         .collect(Collectors.toList()); 

Both functions are BiFunction -- meaning two parameters are required.

ByAuthor receives two parameters: the author name and the article list. The list of filtered articles is returned.

The byTag is the same as the received tag and article LIST parameters. The list of articles filtered by TAG is returned.

Because BiFunction receives two parameters, it only provides the andThen function. You cannot put the result of a function in a function that receives two parameters, so there is no compose function.

To continue, we also have a basic function to sort the list of articles from new to old and return the list of sorted articles.

 
  1. Function<List<Article>, List<Article>> sortByDate =  
  2.     articles -> articles.stream() 
  3.         .sorted((x, y) -> y.published().compareTo(x.published())) 
  4.         .collect(Collectors.toList()); 
  5. Function<List<Article>, Optional<Article>> first =  
  6.     a -> a.stream().findFirst(); 

Now we have basic functions. Now we can see how we use these functions to combine them into new functions.

First, we combine a function to return the list of recently published articles.

 
  1. Function<List<Article>, Optional<Article>> newest =  
  2.     first.compose(sortByDate); 

Use the first function andWeFor the previously created sortByDate, we can create a new function that returns the latest article in the given Article list.

We can continue to mix these functions in different ways, so that we can combine functions of different meanings without repeated code writing.

Find the author's latest article:

 
  1. BiFunction<String, List<Article>, Optional<Article>> newestByAuthor =  
  2.     byAuthor.andThen(newest); 

Or sort the articles of an author.

 
  1. BiFunction<String, List<Article>, List<Article>> byAuthorSorted =  
  2.     byAuthor.andThen(sortByDate); 

Or you may not care about the author. You just want to get the latest article based on your favorite tags:

 
  1. BiFunction<String, List<Article>, Optional<Article>> newestByTag =  
  2.     byTag.andThen(newest); 

The point I want to express is that through the Function INTERFACE AND ITS COMBINATION Function, you can create small code blocks and combine them to meet your needs, in this way, the DRY principle can be implemented more easily and interestingly.

In this case, compose and andThen are used to combine functions in a simple way. Try it too!

 

 

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.