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();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容

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