Acquaintance with the functional programming interface function (a)

At present, most of JAVA8 tutorial we will give up a Lambda expressions, method references, for everyone to do a foggy, eventually leading to JAVA8 learning is not particularly thorough. Let's take a look at what can be used when Lambda expressions, and then explore how to use Lambda expressions.

Starting Functional Programming

The previous section we said, JAVA8 in fact be the result of other languages ​​like Java or some excellent framework for learning. This functional programming concepts presented very early, there are a lot of language support functional programming. In JAVA8 also we do functional programming support. Functional interface concept to introduce the following we are born around functional programming.

  • What is functional programming?

    Simply put, 函数式编程a 编程范式(programming paradigm), which is the methodology of how to write programs. This sentence is Baidu Baike gives us the answer, if you look into this sentence, we might simply can not understand in the end what is 函数式编程.

    We wish to use our most familiar with object-oriented programming ( 命令式编程) analogy a bit, so that we can have a simple concept of functional programming.

    Imperative programming is both a bottom for every word in computer hardware, we write hardware instructions. Functional programming is not one of us 函数is not a function or method we usually written in Java, it is one for the concept of mathematics, it can be understood as an expression or formula, or understood as conversion between data.

    We say do not support functional programming JAVA8 before, what specific manifestation of what you have?

    1. The most important part of the Java classes and objects are no classes and objects, we want to realize the function of the question. Method or function we have defined is a must rely on the class or object to the presence of references now more popular argument, classes and objects are first-class citizens, a process or function called second-class citizens.
    2. Before JAVA8, we can not pass a function as a parameter to a method, the method can not declare a return function.
  • JAVA8 functional programming support to do what?

    JAVA8 by functional interfaces and Lambda expressions introduced the concept of functional programming for us, so that the function in Java also become a first-class citizen.

  • Some of the benefits of functional programming?

    In Java, we can carry out the so-called state variables are changed, such as an age attribute "student" object is in accordance with our needs to change. The functional programming in Java variables are completely different, the mathematical variables is defined, the variable's value is unchangeable. Functional programming though ultimately be compiled into machine instructions to run, but from the ideological aspect of it brought us many benefits, for example, the results will not change the function of time and location of calls varies, run function is independent in the external environment. The greatest advantage is immutable . Because immutability, we do not have the extra locking during multi-threaded operation, they do not care about all kinds of thread safety issues, it is well suited to deal with concurrency issues. This is the same concept in Java immutable (Immutable Object).

We take a look at our programming in the end to bring the benefits JAVA8 after the introduction of functional programming by example.

Our projects often use various elements of the set conditions will be filtered. For example, we define a class of students, we can choose to filter some students based on student scores, filtered through a gender of students, some students filtered out by other conditions.

We take a look at the wording of the beginning:

public static List<Student> selectByMark(List<Student> lists){
  List<Student> result = new ArrayList<>();
  for(Student s:lists){
    if(s.getMark()>60){
      result.add(s);
    }
  }
  return result;
}

public static List<Student> selectBySex(List<Student> lists){
  List<Student> result = new ArrayList<>();
  for(Student s:lists){
    if(s.getSex().equals("Male")){
      result.add(s);
    }
  }
  return result;
}

......
  
.......  selectByName()

We may write write a lot of code as above according to the changing needs in this way. This code is not only redundant and boring, a waste of time equivalent to the programmer.

If you are a somewhat experienced programmer, you would not use the above method to write, but the use of the Strategy pattern design mode to achieve.

//策略接口,一个过滤器
public interface Filter{
  boolean filter(Student s);
}
//不同的实现类,即对学生的过滤方法
public class MarkFilter implements Filter{
  @Override
  public boolean filter(Student s){
    return s.getMark() > 60;
  }
}

public class SexFilter implements Filter{
  @Override
  public boolean filter(Student s){
    return s.getSex().equals("Male");
  }
}

.........
  
  
//给用户提供的静态方法
public static List<Student> select(List<Student> lists, Filter f){
    List<Student> result = new ArrayList<>();
    for(Student s:lists){
      if(f.filter(s)){
         lists.add(s);
      }
    }
    return result;
}

After using the above strategy pattern, in fact, did not have much good, we just put the original static methods into the class. In the actual programming process, we often use anonymous inner classes to implement (pseudo-code), the benefits of this writing, we only define a framework or behavior, specifically how to achieve those calls to be realized. We define the behavior, the user decides to detail.

//调用者需要过滤的时候需要写的代码,Filter 不需要实现类,只需要在调用时 new 一个匿名内部类就可以了。
List<Student> lists = new ArrayList<>();
//lists.add();
List<Student> res = select(lists, new Filter() {
  @Override
  public boolean filter(Student s) {
    return s.getMark()>60;
  }
});

Finally, the solution manner using functional programming, use Lambda expressions, it saves more space than anonymous inner classes, the code cleaner and easier to understand (pseudocode).

//重点
List<Student> result = select(lists,m->m.getMark()>60);

The original object-oriented programming, our method is used to process logic. Now logic or dynamic algorithm is provided when calling. Now see only see a common method or macro logic. It provides a higher level of abstraction. Functional programming, write less, do more.

When we use the original object-oriented programming, when we finished the function, performance function has been fixed, and we want to achieve the even will find a way to write, find a way to write an odd number, find a number greater than 5 to write one way. Functional programming, implementation of the method is an abstract concept, a specific implementation calls for the end user or implemented.

Functional Interface

After understanding the concept of functional programming, we look at JAVA8 to support functional programming what efforts.

First, in Java is reflected in functional programming Lambda 表达式(next chapter we will introduce specific, Lambada 表达式first of all it is an expression, which is the concept of functional programming, it is the anonymous function ).

Lambda expressions in Java but not everywhere can use, if this expression into the Java language to that? Java defines an interface for carrying Lambda expressions, because this interface is functional programming interface design, so called 函数式接口.

Let us help you understand how the function interface:

Recalling the anonymous inner class:

new Thread(new Runnable() {
  @Override
  public void run() {
    System.out.println("this is a thread");
  }
}).start();

This is a more familiar method of starting a thread, Thread class which receives a Runnalbe interface parameters, we need to define an interface class passed in directly using an anonymous inner class here to achieve.

Here incoming Runable interface that meaning is what? Or why such a design that the designer?

This design is when you start a thread, the thread designers just want us to pass specific tasks to be carried out into the like, other features have a good package, users do not need to care about.

This interface encapsulates a behavior, do not pass parameters, return parameters do not achieve specific behavior, behavior that is necessary to execute the specific task thread passed by the caller. Here on the introduction of a concept, function interface is an abstraction for certain acts, a functional interface has only one act.

Similarly Callable interface implementations are his threads, which encapsulates the behavior is not required incoming parameters, but the behavior requires a return value.

Runnable interface functions via the lead interface:

In this interface JAVA8 change is brought about in the above plus a FunctionalInterfacefunctional annotation interface, which is already a proven Runnable interface function, and there is only one parameter without passing, they do not return an abstract method parameters.

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Function interface definition:

By defining functional interfaces we do not see what, in the end what is the function interface, we can look at the source code inside comments in English, here we directly give the definition.

  • The first is a function interface interface.
  • Functional interface must be only an abstract function.
  • In addition to an abstract method other than the function interface allows the default method and static methods (interface and a static method is the default method JAVA8 introduced following sections we will explain in detail).
  • Java.lang.Object abstract method is not counted, abstract methods that may be defined in many java.lang.Object functional interface.
  • If our interface to meet the above conditions but without @FunctionalInterfaceannotation will still be recognized as the compiler function interface.

After reading the definition of interfaces and Runaable we Callable interfaces in retrospect, they fully meet the definition of functional interface.

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

How to create an instance of an interface that?

Since it is the interface, we used to use in certain instances requires creating an interface. There are three ways to create functional interfaces methods Lambda 表达式, 方法引用and 构造方法the way to achieve the following sections will explain the specific method to use Lambda expressions and references.

We turn to the role of Lambda expression is used to create an instance of functional interface.

** Lambda expressions realization:

The following sections we will talk in detail, we can first have a simple impression.

//还是上面那个启动一个线程的例子,因为 Runnable 是一个函数式接口,所以我们可以使用 Lambda 表达式来创建接口实例。
new Thread(() -> System.out.println("this is a thread")).start();

The method implementation referenced:

We understand this may be very difficult, we will speak at the following sections, we can first have a simple impression.

//Lambda 表达式的写法
list.forEach(item-> System.out.println(item));
//方法引用,相当于调用 PrintStream 类的 println 方法
list.forEach(System.out::println);

Achieve constructor is anonymous inner classes we normally use or implement an interface, here it is not described in detail.

Through this chapter, we already know functional programming JAVA8 introduced and how to achieve specific. And clarify the relationship between the reflected functional programming interface function Lambda expressions, and function interface introduces the definition and construction methods, the method also leads to the concept of reference.

Guess you like

Origin www.cnblogs.com/paulwang92115/p/12128494.html