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();
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末铁瞒,一起剝皮案震驚了整個濱河市个绍,隨后出現(xiàn)的幾起案子缩举,更是在濱河造成了極大的恐慌,老刑警劉巖脊另,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡贿讹,警方通過查閱死者的電腦和手機吠裆,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門伐谈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人试疙,你說我怎么就攤上這事诵棵。” “怎么了祝旷?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵履澳,是天一觀的道長。 經(jīng)常有香客問我缓屠,道長奇昙,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任敌完,我火速辦了婚禮储耐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘滨溉。我一直安慰自己什湘,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布晦攒。 她就那樣靜靜地躺著闽撤,像睡著了一般。 火紅的嫁衣襯著肌膚如雪脯颜。 梳的紋絲不亂的頭發(fā)上哟旗,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天,我揣著相機與錄音栋操,去河邊找鬼闸餐。 笑死,一個胖子當(dāng)著我的面吹牛矾芙,可吹牛的內(nèi)容都是我干的舍沙。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼剔宪,長吁一口氣:“原來是場噩夢啊……” “哼拂铡!你這毒婦竟也來了壹无?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤感帅,失蹤者是張志新(化名)和其女友劉穎斗锭,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體留瞳,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡拒迅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了她倘。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片璧微。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖硬梁,靈堂內(nèi)的尸體忽然破棺而出前硫,到底是詐尸還是另有隱情,我是刑警寧澤荧止,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布屹电,位于F島的核電站,受9級特大地震影響跃巡,放射性物質(zhì)發(fā)生泄漏危号。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一素邪、第九天 我趴在偏房一處隱蔽的房頂上張望外莲。 院中可真熱鬧,春花似錦兔朦、人聲如沸偷线。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽声邦。三九已至,卻和暖如春摆舟,著一層夾襖步出監(jiān)牢的瞬間亥曹,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工恨诱, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留媳瞪,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓胡野,卻偏偏與公主長得像,于是被迫代替她去往敵國和親痕鳍。 傳聞我的和親對象是個殘疾皇子硫豆,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 1. 創(chuàng)建生成器 由function*定義的函數(shù)即是generator 2. 生成器的使用
    Vuji閱讀 359評論 0 0
  • 那個女孩龙巨,教會我愛 她曾經(jīng)出現(xiàn)在我的生命里,然后又消失不見 可是熊响,我不相信她是天使 她是世間最普通的女孩 所以我就...
    ArtDream閱讀 203評論 0 0
  • 天氣晴朗旨别,微風(fēng)徐徐,明明已是秋天汗茄,卻讓我有種身處春天的感覺秸弛,那樣的舒適、愜意洪碳、溫暖递览。在文科E樓307教室里,有著墨...
    01cbf6f8ccf2閱讀 335評論 1 7
  • 王菲說:不被上一秒牽掛,不為下一秒擔(dān)憂嫂侍。 貌似無情儿捧,卻明白犀利。她敢這樣說挑宠,也敢于這樣做菲盾,是因為她擁有這樣的傲嬌資...
    丫丫沛閱讀 3,039評論 1 4