Java functional programming (1)

Source: Internet
Author: User

This series of articles is translated from Venkat SubramaniamFunctional Programming in Java


Deepinmind

Chapter 1 hello, lambda expressions! Section 1

The coding style of Java is facing dramatic changes. Our daily work will become simpler, more convenient, and more expressive. Java, a new programming method, has appeared in other programming languages decades ago. After these new features are introduced into Java, we can write code that is more concise, elegant, expressive, and error-less. We can use less code to implement various policies and design patterns. In this book, we will explore functional programming through examples in daily programming. Before using this brand new and elegant method for design coding, let's take a look at what it looks like.

Changing your way of thinking

Imperative style-this method has been provided by the Java language since its birth. To use this style, we have to tell Java what to do in each step, and then let it go through step by step. This is certainly good, and it seems a little Elementary. The code looks a bit cool, and we want the language to be a little smarter. We should tell it what we want rather than how to do it. Fortunately, now Java can finally help us achieve this desire. Let's take a few examples to understand the advantages and differences of this style.

Normal Mode

Let's start with two familiar examples. This is a command to check whether Chicago is a collection of specified cities-remember, the Code listed in this book is only part of the snippet.

boolean found = false;for(String city : cities) {if(city.equals("Chicago")) {found = true;break;}}System.out.println("Found chicago?:" + found);

This imperative version looks awkward and elementary; it is divided into several execution parts. Initialize a Boolean tag named found, and traverse every element in the set. If we find the city we are looking for, set the tag and jump out of the loop body; finally, the search result is printed.

A better way

After careful Java programmers read this code, they will soon come up with a more concise and clear method, like this:

System.out.println("Found chicago?:" + cities.contains("Chicago"));

This is also a imperative style-The contains method can help us solve it directly.

Actual improvements

 

  • The Code has the following advantages:
  • Don't try that variable anymore
  • Encapsulate iterations to the underlying layer
  • Simpler code
  • Clearer and more focused
  • Less detours and closer integration of code and business needs
  • Error-prone
  • Easy to understand and maintain

 

Here is an example of a complex point.

This example is too simple. It is imperative to query whether an element exists in a set that is everywhere in Java. Now let's assume that we want to use imperative programming to perform more advanced operations, such as parsing files, interacting with databases, calling WEB Services, and concurrent programming. Now we can use Java to write code that is more concise, elegant, and has fewer errors, not just this simple scenario.

Old Method

Let's look at another example. We have defined a series of prices and calculated the total price after discount in different ways.

final List prices = Arrays.asList(new BigDecimal("10"), new BigDecimal("30"), new BigDecimal("17"),new BigDecimal("20"), new BigDecimal("15"), new BigDecimal("18"),new BigDecimal("45"), new BigDecimal("12"));

If more than 20 pieces are required, we will take a discount and implement it in a normal way.

BigDecimal totalOfDiscountedPrices = BigDecimal.ZERO;for(BigDecimal price : prices) {if(price.compareTo(BigDecimal.valueOf(20)) > 0)totalOfDiscountedPrices =totalOfDiscountedPrices.add(price.multiply(BigDecimal.valueOf(0.9)));}System.out.println("Total of discounted prices: " + totalOfDiscountedPrices);

This code is very familiar with it; first use a variable to store the total price; then traverse all the prices, find out more than 20, calculate their discount prices, and add them to the total price; finally, the total price after the discount is printed. Below is the output of the program:

Total of discounted prices: 67.5

The results are correct, but the code is messy. This is not our fault. We can only write it in the existing method. However, this code is a bit elementary. It not only has a basic type of paranoia, but also violates the single responsibility principle. If you work at home and have children who want to become coders at home, you have to hide your code. If they see it, they will sigh with disappointment, "You rely on these things to make a living?"

There is a better way

What we can do is better-and much better. Our code is a bit like Requirement Specification. This can narrow the gap between business requirements and implemented code, and reduce the possibility of misunderstanding of requirements. We don't want Java to create a variable and assign it an endless value. We need to communicate with it from a higher level abstraction, just like the following code.

final BigDecimal totalOfDiscountedPrices =prices.stream().filter(price -> price.compareTo(BigDecimal.valueOf(20)) > 0).map(price -> price.multiply(BigDecimal.valueOf(0.9))).reduce(BigDecimal.ZERO, BigDecimal::add);System.out.println("Total of discounted prices: " + totalOfDiscountedPrices);

Read it out loud-filter out the prices of more than 20 items, convert them into discount prices, and add them together. This code is exactly the same as the process for describing the requirement. In Java, you can also easily fold a long line of code, and align the code by line according to the dot before the method name, just like above. The code is very concise, but we use many new things in Java 8. First, we call a stream method of the price list. This opens a door, and there are countless convenient iterators behind it. We will continue to discuss this later. We use some special methods, such as filter and map, instead of directly traversing the entire list. Unlike those in the JDK we used previously, these methods accept an anonymous function-lambda expression-as a parameter. (We will discuss it in depth later ). We call the reduce () method to calculate the total price returned by the map () method. As with the contains method, the loop body is hidden. However, the map (and filter) method is much more complex. It calls the passed lambda expression to calculate each price in the price list and places the result in a new set. Finally, we call the reduce method on this new set to get the final result. This is the output result of the above Code:

Total of discounted prices: 67.5
Improvements

 

  • This is significantly improved compared with the previous implementation:
  • Well-structured but not chaotic
  • No low-level operations
  • Easy to enhance or modify Logic
  • Iterations are performed by the inventory library.
  • High efficiency; Evaluate the cycle body inertia
  • Easy parallelization

 

Next we will talk about how Java implements this.


Lambda expressions to save the world


Lambda expressions are shortcuts that keep us away from imperative programming troubles. This new feature provided by Java has changed our original programming method, so that the code we write is not only concise and elegant, not prone to errors, but also more efficient, easy to optimize, improve, and parallelize.

Deepinmind


For Original article reprinted, please indicate the source: Java translation site

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.