Java8的Function接口以及Lambda表达式Demo

只是简单给出一个小Demo。具体的理论知识可以看后面的参考链接。

package org.fan.func;

import java.util.function.Function;

/** * Created by fan on 2016/11/4. */
public class FunctionDemo {
    //API which accepts an implementation of

    //Function interface

    static void modifyTheValue(int valueToBeOperated, Function<Integer, Integer> function){

        int newValue = function.apply(valueToBeOperated);

        /* * Do some operations using the new value. */

        System.out.println(newValue);

    }

    public static void main(String[] args) {

        int incr = 20;  int myNumber = 10;

        //val-> val + incr
        //相当于定义了一个方法:
        // int function(int val) {
        // return val+incr;
        // }
        modifyTheValue(myNumber, val-> val + incr);

        myNumber = 15;  modifyTheValue(myNumber, val-> val * 10);

        modifyTheValue(myNumber, val-> val - 100);

        modifyTheValue(myNumber, val-> "somestring".length() + val - 100);

    }
}

运行结果:
30
150
-85
-75

参考链接:

  1. 深入浅出 Java 8 Lambda 表达式

  2. Function接口 – Java8中java.util.function包下的函数式接口

  3. 老外写的好文章

  4. Introduction to Functional Interfaces – A concept recreated in Java 8

  5. Using Lambda Expression to sort a List in Java 8 using Netbeans Lambda Support

    原文作者:fan2012huan
    原文地址: https://blog.csdn.net/fan2012huan/article/details/53053683
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞