What do you need to know about Java 8 function programming?

Source: Internet
Author: User
Tags array definition

What do you need to know about Java 8 function programming?

Functional Programming and object-oriented design methods have different ideas and methods. Here, I will briefly introduce some features and differences between functional programming and object-oriented programming.

When understanding the phrase "function as a first-class citizen", let's first look at a very common Internet language JavaScript. I believe everyone will be familiar with it. JavaScript is not strictly functional programming, but it is not strictly object-oriented. However, if you want to, you can treat it as an object-oriented language or a functional language. Therefore, it may be more appropriate to call it a multi-paradigm language.

If you use jQuery, you may frequently use the following code:

$("button").click(function(){    $("li").each(function(){      alert($(this).text())     });   });  

Note that the each () function parameter is an anonymous function.When traversing all the li nodes, the text content of the li node is displayed. Passing a function as a parameter to another function is one of the features of functional programming.

 

Let's examine another case:

function f1(){      var n=1;      function f2(){        alert(n);      }      return f2;    }  var result=f1();  result(); // 1  

This is also a JavaScript code. In this Code, pay attention to the return value of function f1, which returns function f2. In the last 2nd rows, the returned f2 function is assigned to the result. In fact, the result is a function and points to f2. If you call the result, the value of n is printed.

A function can be used as the return value of another function, which is also an important feature of functional programming.

2. No side effects

The side effect of a function indicates that, in addition to the returned value, the function also modifies the external state of the function. For example, when a function is called, modifies a global status. Functional Programming believes that the sub-functions should be avoided as much as possible. As you can imagine, if a function arbitrarily modifies the global or external state, it may be difficult for us to determine which function is causing the problem when the system encounters a problem. This is not good for program debugging and tracking. If all functions are explicit functions, the execution of the functions is obviously not affected by external or global information. Therefore, it is helpful for debugging and troubleshooting.

Note: explicit functions are the only channel through which functions exchange data with the outside world. Explicit functions do not read or modify the external state of functions. In contrast to the implicit function, the implicit function reads external information in addition to parameters and return values, or may modify external information.

However, nothing can be done without any side effects. Because the system always needs to obtain or modify external information. At the same time, interactions between modules are also likely to be performed through shared variables. It is also unpleasant to completely prohibit the appearance of side effects. Therefore, most functional programming languages, such as Clojure, allow side effects. However, compared with object-oriented programming, the side effects of such function calls require effective restrictions in functional programming.

Declarative)

Function programming is Declarative Programming. Compared with imperative programming, imperative programming prefers to use a large number of variable objects and commands. We are always used to creating objects or variables, modifying their statuses or values, or providing a series of commands that require program execution. This programming habit has changed in declarative functional programming. For Declarative Programming Paradigm, you do not need to provide clear instructions for operations. All detailed instructions will be better encapsulated by the library. All you need to do is to put forward your requirements, just declare your intention.

Please refer to the following section of the program, this section of traditional imperative programming, In order to print the values in the array, we need to carry out a loop, and each time we need to determine whether the loop ends. In the loop body, we need to clearly give the statements and parameters to be executed.

 
public static void imperative(){           int[]iArr={1,3,4,5,6,9,8,7,4,2};           for(int i=0;i<iArr.length;i++){                     System.out.println(iArr[i]);           }  }  

The corresponding declarative code is as follows:

public static void declarative(){           int[]iArr={1,3,4,5,6,9,8,7,4,2};           Arrays.stream(iArr).forEach(System.out::println);  }  

As you can see, the loop body of the variable array disappears! The println () function does not seem to specify any parameters here. Here, we simply declare our intention. Operations such as loops and whether or not the loop ends are simply encapsulated in the library.

3. tail recursion Optimization

Recursion is a common programming technique. Recursion can simplify program encoding and greatly reduce the number of lines of code. But recursion has a major drawback-it always uses the stack space. However, the stack space of a program is very limited, which may be several orders of magnitude different from the stack space (the stack space is usually only several hundred kb, the heap space usually reaches several hundred M or even hundreds of GB ). Therefore, large-scale recursive operations may cause stack space overflow errors, which also limits the use of recursive functions and brings certain risks to the system.

Tail recursive optimization can effectively avoid this situation. Tail recursion refers to the last step of a recursive operation in a function. In this case, the work of the function has actually been completed (the rest of the work is to call itself again). At this time, you only need to pass the intermediate result to the recursive function called subsequently. In this case, the compiler can perform an optimization to make the current function call return, or overwrite the frame stack of the old function with the frame stack of the new function. In short, when recursion is at the last step of function operations, we can always find ways to avoid recursive operations from constantly applying for stack space.

Most functional programming languages directly or indirectly support tail recursion optimization.

4. Constant Mode

If you are familiar with multi-threaded programming, you must have all knowledge about the constant mode. The object is not changed after it is created. For example, java. lang. String is a typical constant mode. If you create a String instance in Java, you cannot change the value of the entire String in any case. For example, if you use String. when the replace () function tries to replace a String, in fact, the original String object does not change, and the function itself returns a New String object as the return value after replacement of a given character. Constant objects are widely used in functional programming.

See the following code:

static int[] arr={1,3,4,5,6,7,8,9,10};  Arrays.stream(arr).map((x)->x=x+1).forEach(System.out::println);  System.out.println();  Arrays.stream(arr).forEach(System.out::println);   

Line 1 of the Code seems to have added 1 to each array member. However, after the operation is complete, when printing all the Member values of the arr array in the last row, you will still find that the array members have not changed! In functional programming, this state is normal, and almost all objects are rejected to be modified.

5. Easy Parallel Processing

Because all objects are in the unchanged state, functional programming is easier to parallel. In fact, you don't even have to worry about thread security. One major reason we need to pay attention to thread security is that when multiple threads perform write operations on the same object, it is easy to "Write down" this object ", the more professional statement is to make the object state inconsistent ". However, since the constant mode exists, the object cannot be changed since it was created. Therefore, in a multi-threaded environment, there is no need to perform any synchronization operations. This is not only conducive to parallelization, but also provides better performance because there is no synchronization or lock mechanism after parallelization. Readers can take a look at the java. lang. String object. Obviously, the String object can work well in multiple threads, but every method of it is not synchronized.

6. Less code

In general, functional programming is more concise and concise. Clojure language (a functional language running on JVM) fans claim that, clojure can reduce the number of Java code lines. Generally, simplified code is easier to maintain. Java code redundancy is also well known, and most attacks to the Java language will directly target Java's tedious and rigid syntax (but I think this is also one of the advantages of Java, as mentioned in the first section of this book, "conservative design ideas are the biggest advantage of Java". However, this situation has changed since the introduction of the functional programming paradigm. We can allow Java to do more work with less code.

See the following example. For each member in the array, first judge whether it is an odd number. If it is an odd number, add 1 and print all the members in the array.

Array definition:

  1. Static int [] arr = {1, 3, 4, 5, 6, 7, 8, 9, 10 };
  2. Traditional processing methods:
  3. For (int I = 0; I <arr. length; I ++ ){
  4. If (arr [I] % 2! = 0 ){
  5. Arr [I] ++;
  6. }
  7. System. out. println (arr [I]);
  8. }

 

Function Method:

Arrays. stream (arr). map (x-> (x % 2 = 0? X: x + 1). forEach (System. out: println );

We can see that the functional paradigm is more compact and concise.

If you are interested, please refer to this ebook Java 8 function programming introduction.

 

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.