• Tags ,
  •         
  • www.breakyizhan.com
  •    

    Lambda表达式基本上表示功能接口的实例(具有单个抽象方法的接口称为功能接口。例如java.lang.Runnable)。lambda表达式实现唯一的抽象函数,因此实现了功能接口

    lambda表达式在Java 8中添加,并提供以下功能。

    • 允许将功能视为方法参数,或将代码视为数据。
    • 可以在不属于任何类的情况下创建的函数。
    • lambda表达式可以作为对象传递,并按需执行。

    Java 8中的Lambda表达式

    
    // Java program to demonstrate lambda expressions 
    // to implement a user defined functional interface. 
      
    // A sample functional interface (An interface with 
    // single abstract method 
    interface FuncInterface 
    { 
        // An abstract function 
        void abstractFun(int x); 
      
        // A non-abstract (or default) function 
        default void normalFun() 
        { 
           System.out.println("Hello"); 
        } 
    } 
      
    class Test 
    { 
        public static void main(String args[]) 
        { 
            // lambda expression to implement above 
            // functional interface. This interface 
            // by default implements abstractFun() 
            FuncInterface fobj = (int x)->System.out.println(2*x); 
      
            // This calls above lambda expression and prints 10. 
            fobj.abstractFun(5); 
        } 
    } 
     

    输出:

    10

    lambda表达式
    句法:

     lambda operator -> body

    lambda运算符可以是:

    • 零参数:
      () -> System.out.println("Zero parameter lambda");
    • 一个参数: -
      (p) -> System.out.println("One parameter: " + p);

      如果可以从上下文推断出该变量的类型,则不必使用括号

    • 多个参数:
      (p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);

    请注意:Lambda表达式就像函数一样,它们像函数一样接受参数。

    // A Java program to demonstrate simple lambda expressions
    import java.util.ArrayList;
    class Test
    {
        public static void main(String args[])
        {
            // Creating an ArrayList with elements
            // {1, 2, 3, 4}
            ArrayList<Integer> arrL = new ArrayList<Integer>();
            arrL.add(1);
            arrL.add(2);
            arrL.add(3);
            arrL.add(4);
     
            // Using lambda expression to print all elements
            // of arrL
            arrL.forEach(n -> System.out.println(n));
     
            // Using lambda expression to print even elements
            // of arrL
            arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); }); 
        }
    }
    

    输出:

    1
    2
    3
    4
    2
    4

    请注意,lambda表达式只能用于实现功能接口。在上面的示例中,lambda表达式实现了ConsumerFunctional Interface。

    一个Java程序,用于演示使用两个参数处理lambda表达式。

    // Java program to demonstrate working of lambda expressions
    public class Test
    {
        // operation is implemented using lambda expressions
        interface FuncInter1
        {
            int operation(int a, int b);
        }
     
        // sayMessage() is implemented using lambda expressions
        // above
        interface FuncInter2
        {
            void sayMessage(String message);
        }
     
        // Performs FuncInter1's operation on 'a' and 'b'
        private int operate(int a, int b, FuncInter1 fobj)
        {
            return fobj.operation(a, b);
        }
     
        public static void main(String args[])
        {
            // lambda expression for addition for two parameters
            // data type for x and y is optional.
            // This expression implements 'FuncInter1' interface
            FuncInter1 add = (int x, int y) -> x + y;
     
            // lambda expression multiplication for two parameters
            // This expression also implements 'FuncInter1' interface
            FuncInter1 multiply = (int x, int y) -> x * y;
     
            // Creating an object of Test to call operate using
            // different implementations using lambda Expressions
            Test tobj = new Test();
     
            // Add two numbers using lambda expression
            System.out.println("Addition is " +
                              tobj.operate(6, 3, add));
     
            // Multiply two numbers using lambda expression
            System.out.println("Multiplication is " +
                              tobj.operate(6, 3, multiply));
     
            // lambda expression for single parameter
            // This expression implements 'FuncInter2' interface
            FuncInter2 fobj = message ->System.out.println("Hello "
                                                     + message);
            fobj.sayMessage("Geek");
        }
    }
    

    输出:

    Addition is 9
    Multiplication is 18
    Hello Geek

    重点:

    • lambda表达式的主体可以包含零个,一个或多个语句。
    • 当存在单个语句时,大括号不是必需的,并且匿名函数的返回类型与正文表达式的返回类型相同。
    • 如果有多个语句,则必须用大括号(代码块)括起来,并且匿名函数的返回类型与代码块中返回的值的类型相同,如果没有返回任何内容,则返回void 。

     
    转载请保留页面地址:https://www.breakyizhan.com/java/6495.html