📜  将 Lambda 与Java的接口匹配

📅  最后修改于: 2022-05-13 01:54:55.055000             🧑  作者: Mango

将 Lambda 与Java的接口匹配

最流行和最重要的主题之一是Java的lambda 表达式,但在直接进入我们的讨论之前,让我们深入了解一些重要的事情。从Java中的接口开始,作为接口是类似于类但仅包含抽象方法的引用类型。这是我们在Java 1.8 之前的接口定义。在Java 1.8版本之前,我们使用任何版本,接口分为三种类型,如下所示:

  • 普通接口
  • 与多种方法的接口。
  • 标记接口(接口不包含任何方法)。

函数式接口:函数式接口是一个只包含一个抽象方法的接口,但重要的是要记住它可以有任意数量的默认或静态方法以及对象类方法,因为这最让程序员感到困惑。

例子:

Java
// Java Program to Illustarte Functional Interface
  
// Importing requried classes
import java.io.*;
  
// Interface
@FunctionalInterface
interface display {
  
    // Attribute
    void show(String msg);
  
    // Method
    // To compute the sum
    default int doSum(int a, int b) { return a + b; }
}
  
// Main class implementing the above interface
class GFG implements display {
  
    // Overriding the existing show() method
    @Override
  
    public void show(String msg)
    {
  
        // Print message
        System.out.println(msg);
    }
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating object of class inside main()
        GFG object = new GFG();
  
        // Calling show() method in main()
        object.show("Hello World!");
  
        // Print statement
        System.out.println(object.doSum(2, 3));
    }
}


Java
// Java Program to Illustarte Functional Interface
// With the Usage of Anonymous class
  
// Importing input output classes
import java.io.*;
  
// Interface
@FunctionalInterface
interface Cab {
  
    void bookCab();
}
  
// Main class
class GFG {
  
    // Method 1
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating object of above functional interface
        Cab cab = new Cab() {
            // Method 2
            // Overriding above bookCab() method
            @Override public void bookCab()
            {
  
                // Print statement
                System.out.println(
                    "Booking Successful!! Arriving Soon!!");
            }
        };
  
        cab.bookCab();
    }
}


Java
// Java Program Without UIsing Lambda Expression
  
// Importing all utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // main driver method
    public static void main(String[] args)
    {
  
        // Creating an List of integer type
        List list = Arrays.asList(
            234, 780, 451, 639, 456, 98, 75, 43);
  
        // Printing List before sorting
        System.out.println("Before Sorting");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
  
        // Comparator is a functional interface
        // which is helps to sort object
        Collections.sort(list, new Comparator() {
            // Overriding the existing compare method
            @Override
            public int compare(Integer a1, Integer a2)
            {
  
                return a1 % 10 > a2 % 10 ? 1 : -1;
            }
        });
  
        // Printing the list after sorting
        System.out.println("After Sorting");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
    }
}


Java
import java.io.*;
  
interface Display{
  void show();
}
  
class GFG{
    
  public static void main(String[] args){
    
    Display display= ()->System.out.println("Welcome");
      
    display.show();
       
  }
}


Java
// Java Program to Illustarte Lambda Expression
// with Multiple Parameter
  
// Importing required classes
import java.util.*;
  
// Main class
class GFG {
  
    // main driver method
    public static void main(String[] args)
    {
  
        // Creating a List of integer type
        List list
            = Arrays.asList(24, 346, 78, 90, 21, 765);
  
        // Printing before sorting
        System.out.println("Before sorting.");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
  
        // Sort the integers based on second digit
        Collections.sort(list, (a1, a2) -> {
            return a1 % 10 > a2 % 10 ? 1 : -1;
        });
  
        // Printing after sorting
        System.out.println("After sorting.");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
    }
}


输出
Hello World!
5

此外,现在让我们讨论哪些是匿名类。匿名类只是为了一次性使用而创建的,我们不能重用它。一定想知道为什么我们需要这种类型的类的问题?在某些情况下,例如当我们的唯一目的是覆盖您可以使用的方法时。现在,它的另一个优点是,借助它,我们可以非常轻松地实例化界面。



示例:假设您要预订出租车

Java

// Java Program to Illustarte Functional Interface
// With the Usage of Anonymous class
  
// Importing input output classes
import java.io.*;
  
// Interface
@FunctionalInterface
interface Cab {
  
    void bookCab();
}
  
// Main class
class GFG {
  
    // Method 1
    // Main driver method
    public static void main(String[] args)
    {
  
        // Creating object of above functional interface
        Cab cab = new Cab() {
            // Method 2
            // Overriding above bookCab() method
            @Override public void bookCab()
            {
  
                // Print statement
                System.out.println(
                    "Booking Successful!! Arriving Soon!!");
            }
        };
  
        cab.bookCab();
    }
}
输出
Booking Successful!! Arriving Soon!!

现在是讨论Java的lambda 表达式的好时机。它是Java 8 的重要特性之一。事实上,Lambda 表达式是Java函数式编程的基本方法。它是一个匿名函数,没有名字,不属于任何类,这本身就是一个之前讨论过的大话题。在你知道我们在说什么之前,你必须对它有一个想法。

现在我们已经在登陆之前讨论了所有概念,我们如何将 lambda 表达式与接口匹配?

  • Lambda 表达式仅适用于Java的函数式接口。
  • Lambda 表达式提供了一种清晰简洁的方式来通过表达式来表示方法接口。
  • 它提供了功能接口的实现并简化了软件开发。
  • 借助 Lambda 表达式,我们可以轻松删除样板代码。

句法:

Parameter  -> expression body

让我们以不同的方式查看我们的代码,因为我们之前已经看过一个匿名类示例,因为我们在这里创建了一个整数列表,我们希望根据它们的最后一位数字对它们进行排序。

例子

Java

// Java Program Without UIsing Lambda Expression
  
// Importing all utility classes
import java.util.*;
  
// Main class
class GFG {
  
    // main driver method
    public static void main(String[] args)
    {
  
        // Creating an List of integer type
        List list = Arrays.asList(
            234, 780, 451, 639, 456, 98, 75, 43);
  
        // Printing List before sorting
        System.out.println("Before Sorting");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
  
        // Comparator is a functional interface
        // which is helps to sort object
        Collections.sort(list, new Comparator() {
            // Overriding the existing compare method
            @Override
            public int compare(Integer a1, Integer a2)
            {
  
                return a1 % 10 > a2 % 10 ? 1 : -1;
            }
        });
  
        // Printing the list after sorting
        System.out.println("After Sorting");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
    }
}
输出

Before Sorting
234 780 451 639 456 98 75 43 
After Sorting
780 451 43 234 75 456 98 639 

Lambda 表达式的特征

  • 可选类型声明
  • 参数周围的可选括号。
  • 一行代码的可选花括号。
  • 可选的返回关键字。

示例 1参数为零的 Lambda 表达式

Java

import java.io.*;
  
interface Display{
  void show();
}
  
class GFG{
    
  public static void main(String[] args){
    
    Display display= ()->System.out.println("Welcome");
      
    display.show();
       
  }
}
输出
Welcome

示例 2:具有多个参数的 Lambda 表达式

Java

// Java Program to Illustarte Lambda Expression
// with Multiple Parameter
  
// Importing required classes
import java.util.*;
  
// Main class
class GFG {
  
    // main driver method
    public static void main(String[] args)
    {
  
        // Creating a List of integer type
        List list
            = Arrays.asList(24, 346, 78, 90, 21, 765);
  
        // Printing before sorting
        System.out.println("Before sorting.");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
  
        // Sort the integers based on second digit
        Collections.sort(list, (a1, a2) -> {
            return a1 % 10 > a2 % 10 ? 1 : -1;
        });
  
        // Printing after sorting
        System.out.println("After sorting.");
  
        for (int i : list)
            System.out.print(i + " ");
  
        System.out.println();
    }
}
输出
Before sorting.
24 346 78 90 21 765 
After sorting.
90 21 24 765 346 78