"Turn" JAVA8 study notes (1)--from the functional interface

Source: Internet
Author: User
Tags instance method iterable

http://blog.csdn.net/zxhoo/article/details/38349011

Function-Type interface

Understanding the functional Interface (functional interface, FI) is the key to learning Java8 lambda expressions, so put it at the very beginning of the discussion. The definition of fi is very simple: any interface, if it contains only one abstract method, then it is a fi. In order for the compiler to help us ensure that an interface satisfies the requirements of fi (that is, there is only one abstract method), JAVA8 provides @functionalinterface annotations. To give a simple example, the Runnable interface is a fi, and here is its source code:

[Java]View PlainCopy
    1. @FunctionalInterface
    2. Public interface Runnable {
    3. public abstract Void run ();
    4. }

Lambda syntax sugar

In order to create an instance of fi in a convenient, fast and elegant way, JAVA8 provides a lambda expression, the syntactic sugar. Here I use an example to introduce the lambda syntax. Suppose we want to sort a list<string> by the length of a string, then the anonymous inner class can be implemented before JAVA8:

[Java]View PlainCopy
    1. list<string> words = arrays.aslist ("Apple", "banana", "pear");
    2. Words.sort (new comparator<string> () {
    3. @Override
    4. public int Compare (string w1, String w2) {
    5. return Integer.compare (W1.length (), w2.length ());
    6. }
    7. });

The anonymous inner class above can be described as ugly, the only line of logic is drowned in the five-piece garbage code. Based on the previous definition (and looking at the Java source code), comparator is a fi, so it can be implemented with lambda expressions:

[Java]View PlainCopy
    1. Words.sort (String w1, String w2), {
    2. return Integer.compare (W1.length (), w2.length ());
    3. });

The code shortened a lot! A closer look will reveal that the lambda expression is much like an anonymous method, except that the argument list inside the parentheses and the code inside the curly braces are separated. The less garbage code is written, the more time we have to write real logic code, right? Yes! The type of argument in parentheses can be omitted:

[Java]View PlainCopy
    1. Words.sort ((W1, W2), {
    2. return Integer.compare (W1.length (), w2.length ());
    3. });

If the code block of a lambda expression is just a return followed by an expression, it can be further simplified:

[Java]View PlainCopy
    1. Words.sort (
    2. (W1, W2), Integer.compare (W1.length (), W2.length ())
    3. );

Note that there is no semicolon after the expression! If there is only one parameter, then the parentheses enclosing the parameter can be omitted:

[Java]View PlainCopy
    1. Words.foreach (Word, {
    2. SYSTEM.OUT.PRINTLN (word);
    3. });

What if an expression does not require arguments? Well, that must also have parentheses, for example:

[Java]View PlainCopy
    1. Executors.newsinglethreadexecutor (). Execute (
    2. (), {/* do something. * /}//Runnable
    3. );

Method reference

Sometimes the code for a lambda expression is just a simple method call, and in this case, the lambda expression can be further simplified as a method References. There are four forms of method references, the first of which refers to static methods , such as:

[Java]View PlainCopy
    1. list<integer> ints = arrays.aslist (1, 2, 3);
    2. Ints.sort (Integer::compare);

The second way to refer to an instance of a particular object , such as the previous one that iterates through and prints each word, can be written like this:

[Java]View PlainCopy
    1. Words.foreach (System.out::p rintln);

The third type of instance method that references a class , for example:

[Java]View PlainCopy
    1. Words.stream (). Map (Word, word.length ()); //Lambda
    2. Words.stream (). Map (String::length); //Method reference

The fourth kind of constructor that references a class, for example:

[Java]View PlainCopy
    1. Lambda
    2. Words.stream (). Map (Word, {
    3. return new StringBuilder (word);
    4. });
    5. Constructor reference
    6. Words.stream (). Map (StringBuilder::new);

When to use lambda expressions

Since lambda expressions are so useful, where can they be used? If you really understand what fi is (it's easy), you should be able to answer it right away: any place where you can accept an instance of FI, you can use a lambda expression. For example, although the example given above is passing a lambda expression as a method parameter, you can actually define the variable as well:

[Java]View PlainCopy
    1. Runnable task = (), {
    2. //Do something
    3. };
    4. Comparator<string> cmp = (S1, s2), {
    5. return Integer.compare (S1.length (), s2.length ());
    6. };

Pre-defined functional interfaces

Java8 in addition to Runnable,comparator and other interfaces on the @functionalinterface annotation, but also pre-defined a large number of new fi. These interfaces are in the Java.util.function package, the following is a brief introduction to several of them.

[Java]View PlainCopy
    1. @FunctionalInterface
    2. Public interface Predicate<t> {
    3. Boolean test (T T);
    4. }

predicate is used to determine whether an object satisfies a certain condition, such as whether the word consists of more than six letters:

[Java]View PlainCopy
    1. Words.stream ()
    2. . Filter (Word, word.length () > 6)
    3. . Count ();

A function that represents an argument that receives a parameter and produces a result:

[Java]View PlainCopy
    1. @FunctionalInterface
    2. Public Interface Function<t, r> {
    3. R apply (t T);
    4. }

The following example multiplies each integer in the collection by 2:

[Java]View PlainCopy
    1. Ints.stream (). Map (x-X * 2);

Consumer represents an operation on a single parameter, which is the parameter received by the foreach () method in the preceding example:

[Java]View PlainCopy
    1. @FunctionalInterface
    2. Public interface Consumer<t> {
    3. void Accept (T t);
    4. }

Enhancements to Legacy APIs

To give full play to the power of lambda, JAVA8 has enhanced many of the old class libraries and equipped them with lambda weapons. For example, the foreach () method used in the previous example is actually added to the Iterable interface. The stream () method, which appears multiple times, is added to the collection interface. Java programmers who have used languages such as Ruby,scala,groovy may have long coveted external iterator patterns that are well implemented in these languages. While Google's guava can compensate for Java's flaws in some way, Java8 's lambda really makes Java a big step towards functional programming.

Default methods for interfaces

The attentive reader may find a problem, adding methods to interfaces such as iterable and collection, would it not break the interface backwards compatibility? Yes, in order to ensure the backward compatibility of the API, JAVA8 has made a large adjustment to the syntax of the interface, adding the default method, which is Methods. The following is the implementation code for the foreach () method:

[Java]View PlainCopy
  1. Public interface Iterable<t> {
  2. ...
  3. default void ForEach (consumer<? Super t> Action) {  
  4. Objects.requirenonnull (action);
  5. For (T T: this ) {
  6. Action.accept (t);
  7. }
  8. }
  9. ...
  10. }

static methods for interfaces

In addition to the abstract method and the default method, the interface can have static methods, starting with Java8. With this syntax, we can define interface-related helper methods (helper Methods) directly in the interface. For example, a function interface defines a factory method indentity ():

[Java]View PlainCopy
  1. Public Interface Function<t, r> {
  2. ...
  3. /** 
  4. * Returns a function that all Returns its input argument.
  5. *
  6. * @param <T> The type of the input and output objects to the function
  7. * @return A function that all returns its input argument
  8. */
  9. static <T> function<t, t> identity () {
  10. return T-t;
  11. }
  12. ...
  13. }

Variable capture

Like inner classes, lambda can also access external (lexical scope) variables, which are basically the same rules. Before Java8, the inner class could only access variables of the final type, Java8 relaxed the limit, as long as the variable was actually immutable (effectively final). In other words, if you add the final keyword compiler to the variable without an error, then when you remove the final keyword, it is effectively final. Look at the following example:

[Java]View PlainCopy
    1. int a = 100;
    2. Runnable x = new Runnable () {
    3. @Override
    4. public Void Run () {
    5. System.out.println (a);
    6. }
    7. };

Before Java8, a must be final in order to be seen by X. The following example is rewritten with a lambda expression:

[Java]View PlainCopy
    1. int a = 100;
    2. Runnable x = (), {
    3. System.out.println (a);
    4. };
Conclusion

As you can see, JAVA8 has made great adjustments to the Java language in order to support lambda expressions. But the lambda expression is not just Java syntax sugar, but is implemented by the compiler and the JVM together, which I'll cover in the next article.

"Turn" JAVA8 study notes (1)--from the functional interface

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.