Java Lambda表达式面试问答

x33g5p2x  于4个月前 转载在 Java  
字(5.7k)|赞(0)|评价(0)|浏览(111)

在本文中,我们将讨论一些重要的常见问题Java Lambda表达式面试问答。
通过《Lambda表达式指南》中的示例了解Java 8 Lambda公式。

1.什么是Lambda表达式?

Lambda表达式只是一个没有名称的函数。它甚至可以用作函数中的参数。Lambda Expression简化了函数式编程,大大简化了开发过程。
Lambda表达式的主要用途是为函数接口提供实现

**示例1:**Lambda表达式提供了Printable函数接口的实现:

interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
         // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}

输出:

Print message to console....
 Print message to console....

**示例2:**创建一个以lambda表达式作为参数的方法:

interface StringFunction {
    String run(String str);
}

public class Main {
     public static void main(String[] args) {
       StringFunction exclaim = (s) -> s + "!";
       StringFunction ask = (s) -> s + "?";
       printFormatted("Hello", exclaim);
       printFormatted("Hello", ask);
    }
    public static void printFormatted(String str, StringFunction format) {
       String result = format.run(str);
       System.out.println(result);
     }
}

**示例3:**将lambda表达式作为参数传递给构造函数

static Runnable runnableLambda = () -> {
        System.out.println("Runnable Task 1");
        System.out.println("Runnable Task 2");
    };
   //Pass lambda expression as argument
    new Thread(runnableLambda).start();

详细阅读Java 8 lambda表达式中的lambda表达式

2.为什么使用Lambda表达式?

1.促进函数编程-Lambda Expression促进函数编程并大大简化开发。
1.提供Java 8功能接口的实现。
1.代码行数减少-使用lambda表达式的一个明显好处是减少了代码量,我们已经看到,使用lambda表达式而不是使用匿名类创建函数接口的示例是多么容易。
1.将行为传递到方法-Lambda表达式使您能够封装单个行为单元并将其传递给其他代码。例如,对其他方法或构造函数。
在Java 8 lambda expressions上阅读有关lambda表达式的更多详细信息。

3.解释Lambda表达式语法

Java Lambda表达式语法:

(argument-list) -> {body}

Java lambda表达式由三个组件组成。

***参数列表:**也可以为空或非空。
***箭头标记:**用于链接参数列表和表达式主体。
***正文:**它包含lambda表达式的表达式和语句。

例如,假设我们有一个功能接口:

interface Addable{  
    int add(int a,int b);  
}


让我们使用lambda表达式实现上述Addable函数接口:

Addable withLambdaD = (int a,int b) -> (a+b);  
        System.out.println(withLambdaD.add(100,200));

在Java 8 lambda expressions上阅读有关lambda表达式的更多详细信息。

4.以下哪项是有效的lambda表达式? 

A.

String a, String b -> System.out.print(a+ b);

B

() -> return;

C

(int i) -> i;

D

(int i) -> i++; return i;

答案

正确答案是C。

解释

选项C有效。如果主体只有一条语句,则不需要使用return关键字。

5.编写Java Lambda表达式以创建线程

Runnable接口是一个函数接口,因此我们可以使用Lambda表达式实现Runnable函数接口。

示例:

public class JLEExampleRunnable {

    public static void main(String[] args) {
  
    //without lambda, Runnable implementation using anonymous class  
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println(" Runnable example without lambda exp.");
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
  
     //with lambda 
    Runnable withLambda = () -> System.out.println(" Runnable example with lambda exp.");
    Thread thread1 = new Thread(withLambda);
    thread1.start();
  }
}

输出:

Runnable example without lambda exp.
 Runnable example with lambda exp.

6.Lambda表达式和功能接口是如何关联的?

Lambda表达式的主要用途是为函数接口提供实现
例如,Lambda表达式提供了Printable函数接口的实现:

interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
         // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}

输出:

Print message to console....
 Print message to console....

7.解释书写Lambda表达式的各种形式?

无参数的Java Lambda表达式:

interface Sayable {
    public String say();
}
public class JLEExampleNoParameter {
    public static void main(String[] args) {
        // without lambda expression
        Sayable sayable = new Sayable() {
            @Override
            public String say() {
                return "Return something ..";
            }
        };
        sayable.say();

        // with lambda expression
        Sayable withLambda = () -> {
            return "Return something ..";
        };
        withLambda.say();
    }
}

具有单个参数的Java Lambda表达式:

interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
     // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}

输出:

Print message to console....
 Print message to console....

具有多个参数的Java Lambda表达式:

interface Addable{  
    int add(int a,int b);  
}  
public class JLEExampleMultipleParameters {

 public static void main(String[] args) {
  
     // without lambda expression
  Addable addable = new Addable() {
   @Override
   public int add(int a, int b) {
    return a + b;
   }
  };
  addable.add(10, 20);
  
  // with lambda expression
   // Multiple parameters in lambda expression  
        Addable withLambda = (a,b)->(a+b);  
        System.out.println(withLambda.add(10,20));  
          
        // Multiple parameters with data type in lambda expression  
        Addable withLambdaD = (int a,int b) -> (a+b);  
        System.out.println(withLambdaD.add(100,200));  
 }
 
}

正文中包含多个语句的Java Lambda表达式:

interface IAvarage{  
    double avg(int[] array);  
}  
public class JLEExampleMultipleStatements {

    public static void main(String[] args) {
  
        // without lambda expression, IAvarage implementation using anonymous class  
         IAvarage avarage = new IAvarage() {
            @Override
            public double avg(int[] array) {
                double sum = 0;
                int arraySize = array.length;
    
                System.out.println("arraySize : " + arraySize);
                for (int i = 0; i < array.length; i++) {
                    sum = sum + array[i]; 
                } 
                System.out.println("sum : " + sum);
    
                return (sum/ arraySize);
           }
        };
        int[] array = {1,4,6,8,9};
        System.out.println(avarage.avg(array));
  
        // with a lambda expression
        // You can pass multiple statements in lambda expression 
  
        IAvarage withLambda = (withLambdaArray) -> {
            double sum = 0;
            int arraySize = withLambdaArray.length;
   
            System.out.println("arraySize : " + arraySize);
            for (int i = 0; i < withLambdaArray.length; i++) {
                sum = sum + withLambdaArray[i]; 
            }
            System.out.println("sum : " + sum);
   
            return (sum/ arraySize);
       };
  
        int[] withLambdaArray = {1,4,6,8,9};
        System.out.println(withLambda.avg(withLambdaArray)); 
    }
}

相关文章