Java8 Learning Chapter | (i) Introduction to functional programming __div

Source: Internet
Author: User
Tags readable

the transformation of the way of thinking

To look for the existence of Chicago from a collection of cities: The customary way

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

The code above is the first response of most developers to this problem. It accomplishes the logic needed through the imperative style code, but it looks more complicated because of the amount of code.

Experienced developers use existing APIs to make the code simpler and more readable, because it transforms the code style from imperative to declarative (declarative style).

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

Simple line of code, you can show the intent of the program. Another example

Suppose for more than 20 yuan of goods, 90 percent processing, and finally get the price of these goods after the discount. The following solutions are immediately reflected in your mind:

  final list< bigdecimal> prices = arrays.aslist (new BigDecimal ("Ten"), New BigDecimal ("a"), New BigDecimal ("M"), new Bigde

Cimal ("A"), New BigDecimal ("a"), New BigDecimal ("a"), New BigDecimal ("a"), New BigDecimal ("12"));
BigDecimal totalofdiscountedprices = Bigdecimal.zero; for (BigDecimal price:prices) {if Price.compareto (bigdecimal.valueof) > 0) totalofdiscountedprices =
Totalofdiscountedprices.add (Price.multiply (bigdecimal.valueof (0.9))); } System.out.println ("Total of discounted prices:" + totalofdiscountedprices);  

When you write this type of code on a regular basis, you don't know whether it will create a feeling of boredom or discomfort. Because this code is a little bit boring, although it can work, but always feel that it is not so elegant.

The more elegant way is to use declarative code:

Final BigDecimal totalofdiscountedprices = Prices.stream ()
    . Filter (Price-> Price.compareto ( bigdecimal.valueof) > 0)
    . Map (Price-> price.multiply (bigdecimal.valueof (0.9))
    . Reduce ( Bigdecimal.zero, Bigdecimal::add);

SYSTEM.OUT.PRINTLN ("Total of discounted prices:" + totalofdiscountedprices);

There is no declaration of any temporary variables, no various if judgments, logical coherent. It is also more readable: first filter the price set according to criteria, then discount the filtered collection (map), and finally add the price after the discount (reduce).

It leverages the new features of Java 8, lambda expressions, and associated methods such as stream (), reduce (), and so on to transform the code into functional style (functional style). The lambda expression and its related content are described in detail in the following article. The benefits of using functional code reduce the amount of variable (immutable Variable) declarations to make better use of parallel (Parallelism) code to be more concise and readable

Of course, the introduction of functional programming styles in Java 8 is not intended to subvert the already ingrained object-oriented programming style. But let them coexist harmoniously and learn from each other. For example, objects are modeled on entities, relationships between entities are expressed, and functional codes are used to implement various state changes in the entity, business processes, and data processing. The core of functional programming

Declarative code style (declarative style): This requires an abstraction of the code, for example, in the previous example, to encapsulate an action from a collection to an element in the Contains method.

More invariance (Promote immutability): Do not declare a variable without declaring it, and use final to modify the variables when needed. Because the more variables, it means that the more difficult the process of parallelism. The method of achieving invariance means that it no longer has side effects and does not change the state of the program because of the call.

Use an expression instead of a statement (prefer Expression to Statement): Using a statement also means invariance and changes in the state of the program, such as the use of assignment statements.

Using higher-order functions (High-order function): Before Java 8, reuse was built on objects and type systems. In Java 8, the concept of reuse is further, and the use of functions enables code reuse. The so-called higher order function, not to be intimidated by its name, is actually very simple: pass a function as an argument to another function the return value of a function can be a function type to create another function in a function

In the preceding article, you have seen an example of a function being passed into another function as a parameter:

Prices.stream ()
    . Filter (Price-> Price.compareto (bigdecimal.valueof) > 0)
    . Map (Price-> Price.multiply (bigdecimal.valueof (0.9)))
    . Reduce (Bigdecimal.zero, bigdecimal::add);

Price -> price.multiply (bigdecimal.valueof (0.9)) is actually a function. But it's written using a lambda expression, which is converted to a function when the code is executed. Functional Interface (functional Interface)

To introduce functional programming into Java, the concept of functional interfaces is introduced in Java 8.

A functional interface is one that declares only the interface of a method, such as the familiar runnable,callable,comparable, which can be used as a functional interface. Of course, in Java 8, a new type of functional interface, such as Function,predicate,consumer,supplier, is added.

In a functional interface, you can declare 0 or more default methods, which are already implemented within the interface. Therefore, the default method of the interface is also a new concept introduced in Java 8.

Functional interfaces are annotated with @functionalinterface annotations. Although the use of this annotation is not mandatory, the benefit of using it is to make the purpose of this interface more explicit, and the compiler will also check the code to ensure that the interface annotated by the annotation has no syntax errors.

If a method accepts a functional interface as an argument, then we can pass in the following types as arguments: the anonymous inner class (Anonymous Inner Class) lambda expression method or the constructor's reference (a or constructor Reference)

The first is a way that is often used in previous versions of Java and is no longer recommended in Java 8. In the second approach, the lambda expression is converted to an instance of the corresponding functional interface by the compiler. The third way is described in detail in the following article.

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.