Functional Programming in Java 8

@FunctionalInterface

Functional interface annotation has been introduced in Java8, which permit exactly one abstract method inside them. Instances of this interface can be constructed from lambda expression or method reference.
In fact, the concept of FunctionalInterface has the same meaning of Single Abstract Method interfaces (SAM Interfaces), there are some SAM intefaces before JDK 8 released:

java.lang.Runnable

@FunctionalInterface
public interface Runnable {
   
   public abstract void run();
}

java.util.concurrent.Callable

java.io.FileFilter...

Define a functional interface

sample code as following:

@FunctionalInterface
public interface MyFunctionalInterface<T, E extends Exception> {
    
    T call() throws E;

    default void doMore() {
        //do something more here.
    }

    @Override
    String toString();
}

Note that, we only declared one abstract method in this interface. The @FunctionalInterface is added for static grammar check, it also works as a functional interface even if we ommit the annotation.

Default method

JDK 8 allows us put default method in an interface, which means interface will not only include abstract methods as before.
For example, if we defined such an interface:

public interface MyInterface {
    void doSomething();

    default void doMore() {
        //do more things here
    }
}

The class implements this interface won't have to implement default methods:

public class MyClass implements MyInterface {

    @Override
    public void doSomething() {
        // TODO
    }

}

Lambda expression

Lambda expression has the same action as anonymous function. As we said lambda expression will produce a FunctionalInterface instance, so some SAM interfaces can be easily converted to lambda expression.
We may use following code to start a new thread without lambda:

new Thread(new Runnable() {
            
    @Override
    public void run() {
        doSomething();
    }
}).start();

When using lambda, the code will be very simple:

new Thread(() -> doSomething()).start();

The lambda expression can transfer certain parameters. Firstly, we declared a SAM interface:

public interface MyInterface {
    int add(int a, int b);
    
    default void doExtra(){
        
    }
}

Now we will use lambda expression to implement this interface:

MyInterface myInterface = (a,b) -> a+b;
myInterface.add(3,5);

Method reference

It is introduced to simpify lambda expression, we can use class/instance name::method name to locate certain method.
There are different usage of method reference. Define a class as following:

public class MyClass {
    private int id;
    public MyClass(int id){
        this.id = id;
    }

    public static String method() {
        return "Something";
    }

    public int getId(){
        return id;
    }
}
  • Static method
    Myclass::method
  • Instance method
    MyClass clazz = new MyClass(2);
    clazz::getId
  • Custrutor method
    MyClass::new

Method invoker code sample

Now we will use functional interface to create a method invoker class, which allow us to invoke a method using method reference.
There are some interfaces should be created:

@FunctionalInterface
public interface DefaultMethodFunction<T, E extends Exception> {
    
    T call() throws E;
    
}
@FunctionalInterface
public interface MethodFunction<P, T, E extends Exception> extends DefaultMethodFunction<T, E> {
    default T call() {
        return null;
    }
    
    T call(P param) throws E;
}

The DefaultMethodFunction interface carries one abstract method without any parameters, so if we transferred in a method reference without arguments, then it will look for this interface's implementation. MethodFunction carrys one paramter and returns any type extends Object. More functional interfaces can be created if we need to adapt to various method reference.

public class UnderTest {
    
    public static String method(){
        return "Something";
    }
    
    public static String add(int a){
        return String.format("Params: %d", a);
    }

    public static void main(String[] args) {
        System.out.println(MethodInvoker.call(UnderTest::method));
        System.out.println(MethodInvoker.call(UnderTest::add, 3));
    }
}

The m method of UnderTest has no parameters, so its method reference will be considered as instance of DefaultMethodFunction interface.
The MethodInvoker is given as following:

public class MethodInvoker {
    
    public static <T, E extends Exception> T call(DefaultMethodFunction<T, E> function) throws E {
        return  function.call();
    }
    
    public static <T, E extends Exception, P> T call(MethodFunction<P, T, E> function, 
            P param) throws E {
        return function.call(param);
    }
}

Difference between static method reference & static call using class name:

Function Api

Funtional programming has been supported in JDK 8, most interface can be found in package java.util.function. Function,Consumer,Predicate,Supplier and other functional interfaces are widely used in api that support lambda expression.

Function

@FunctionalInterface
public interface Function<T, R> {
  R apply(T t);
  default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
       Objects.requireNonNull(before);
       return (V v) -> apply(before.apply(v));
   }
...
}
  • R apply(T t), this method can be override by lambda expression, it consume one parameter and return the real result.

Code sample:

import java.util.function.Function;

public class Test {
    public static void main(String[] args) {
        Function<Integer, Function<Integer, Integer>> changeValue = FunctionHelper::changeValue;
        System.out.println(changeValue.apply(2).apply(100));//102
    }
}

class FunctionHelper {

    static Function<Integer, Integer> changeValue(int orginal){
        return var -> orginal + var;
    }
}

Predicate

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
}

There are other 4 default methods in Predicate.

Cosumer

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Note that, the accept consumes one parameter, invoke this method may change the original state of that parameter.

  • Code sample:
    We will use Consumer & Predicate interface to judge level of given value.
class Result {
    private int value;
    private String level;

    public Result(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }
}

public class Test {
    public static void main(String[] args) {
        Result result = new Result(72);
        result = updateValue(result,
                var -> var.getValue() > 0,
                var -> {
                    if(var.getValue() >= 60 && var.getValue() < 80){
                        var.setLevel("C");
                    } else if (var.getValue() >= 80 && var.getValue() < 90) {
                        var.setLevel("B");
                    } else
                        var.setLevel("A");
                });
        System.out.println(result.getLevel());//C
        
    }
    
    static Result updateValue(Result result, Predicate<Result> predicate, Consumer<Result> consumer) {
        if(predicate.test(result))
            consumer.accept(result);
        return result;
    }
}

The updateValue method takes Result,Predicate,Consumer as parameters, so when we call this method we should implement Predicate & Consumer interface.

Supplier

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

This interface allows us to create a function that can supply series of objects.

  • Code sample

First, we will define the BusinessObject interface:

interface BusinessObject{
    BusinessObject save();
}

Now, we will add some implementations of this interface:

class User implements BusinessObject{

    @Override
    public BusinessObject save() {
        System.out.println("Saved:"+this.toString());
        return this;
    }
}

class Customer implements BusinessObject{

    @Override
    public BusinessObject save() {
        System.out.println("Saved:"+this.toString());
        return this;
    }
}

If we want to save an instance of BusinessObject, we needn't care about its true type. So we will use Supplier to get an object.

public class Test {
    public static void main(String[] args) {
        save(User::new);
        save(Customer::new);
    }
    
    static <T extends BusinessObject> BusinessObject save(Supplier<T> supplier){
        BusinessObject bo = supplier.get();
        return bo.save();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1. 创建生成器 由function*定义的函数即是generator 2. 生成器的使用
    Vuji阅读 405评论 0 0
  • 那个女孩,教会我爱 她曾经出现在我的生命里,然后又消失不见 可是,我不相信她是天使 她是世间最普通的女孩 所以我就...
    ArtDream阅读 246评论 0 0
  • 天气晴朗,微风徐徐,明明已是秋天,却让我有种身处春天的感觉,那样的舒适、惬意、温暖。在文科E楼307教室里,有着墨...
    01cbf6f8ccf2阅读 421评论 1 7
  • 王菲说:不被上一秒牵挂,不为下一秒担忧。 貌似无情,却明白犀利。她敢这样说,也敢于这样做,是因为她拥有这样的傲娇资...
    丫丫沛阅读 3,302评论 1 4

友情链接更多精彩内容