Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active March 18, 2016 21:07
Show Gist options
  • Select an option

  • Save simonwoo/bcdaecdd19f121564840 to your computer and use it in GitHub Desktop.

Select an option

Save simonwoo/bcdaecdd19f121564840 to your computer and use it in GitHub Desktop.

函数接口

java8中共提供一下几类函数接口:

  • Function: To represent a function that takes an argument of type T and returns a result of type R.
public interface Function<T,R>{
   ...
   public R apply(T t);
   ...
}
  • Supplier: To represent a function that returns a value as of type T.
public interface Supplier<T>{
   ...
    public T get();
   ...
}
  • Consumer: To represent an operation that takes an argument and returns no result.
public interface Consumer<T>{
   ...
   public void accept(T t);
   ...
}
  • Predicate: To represent a boolean function that returns true or false for the specified argument.
public Predicate<T> {
   ...
   public boolean test(T  t);
   ...
}
  • BiFunction: To represent a function that takes two arguments of types T and U, and returns a result of type R.
public interface BiFunction<T,U,R>{
   ...
   public R apply(T t, U u);
   ...
}   
  • ...

A lambda expression represents an instance of a functional interface.The type of a lambda expression is a functional interface type. (String str) -> str.length() takes a String parameter and returns its length.

The following is an example of such a functional interface:

@FunctionalInterface
interface Processor  {
    int  getStringLength(String str);
}

We can assign lambda expression to its functional interface instance.

Processor stringProcessor = (String str) -> str.length();

A functional interface is an interface that has one abstract method. We cannot use the following types of methods to declare a functional interface:

  • Default methods
  • Static methods
  • Methods inherited from the Object class

A functional interface can redeclare the methods in the Object class. And that method is not counted as abstract method. Therefore we can declare another method used by lambda expression.

Consider the Comparator class in the java.util package, as shown:

package java.util;

@FunctionalInterface
public interface  Comparator<T> {
   // An  abstract method  declared in the functional interface 
   int compare(T  o1,   T  o2);

   // Re-declaration of the equals() method in the Object class 
   boolean equals(Object  obj);

   ...
}

The Comparator interface has two abstract methods: compare() and equals().The equals() method is a redeclaration of the equals() method from the Object class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment