菜鸡小白为了巩固才写的。
Lambda 表达式是 Java 8 引入的一种功能,用于实现函数式接口的匿名方法。使用 Lambda 表达式可以简化代码,使代码更简洁和易读。下面是 Java Lambda 表达式的基本模板和一些示例。更加遍历的来形容也就是说,对于一种函数式接口,同时它又且只有一个抽象类方法(方法并不唯一)
一、Lambda 表达式的基本模板
Lambda 表达式的基本语法形式为:
(parameters) -> expression
或者
(parameters) -> { statements; }
组成部分
- 参数列表:也就是->左边的括号,可以有一个或多个参数(根据要创造的抽象类方法的接口而决定)。如果只有一个参数,可以省略小括号;如果没有参数,必须用
()
表示。 - 箭头符号:用
->
分隔参数和方法体。 - 方法体:
- 如果方法体只有一行,可以直接写表达式。
- 如果方法体有多行,必须用
{}
包裹,并且可以包含多个语句。如果只有一条语句,大括号可以省去。
二、常见的函数式接口
在 Java 中,有一些内置的函数式接口可以与 Lambda 表达式一起使用。常见的包括:
-
Function:接收一个参数并返回一个结果。
-
模板:
Function<T, R>
-
例子:
import java.util.function.Function; public class FunctionExample { public static void main(String[] args) { Function<Integer, Integer> square = x -> x * x; System.out.println(square.apply(5)); // 输出: 25 } }
Function这个函数接口,它必须要两个形参,第一个T是输入的形参,第二个是输出的形参,形参是泛型,根据<>里面所输入的引用类型来决定,像该例子里面是<Integer,Integer>,所以输入的是Integer引用类型,输出也是Integer引用类型。那么结果就是 25 .如果将例子改为
-
import java.util.function.Function; public class Try1 { public static void main(String[] args) { Function<Integer,String> d1 = (value) -> "Hello World"; System.out.println(d1.apply(1)); } }
那么就可以得到输出是String类型,输入是Integer。输出就是Hello World。
-
-
Consumer:接收一个参数并且没有返回值。
-
模板:
Consumer<T>
-
例子:
import java.util.function.Consumer; public class ConsumerExample { public static void main(String[] args) { // 定义一个 Consumer 类型的变量,接收一个 Lambda 表达式 Consumer<String> printMessage = message -> System.out.println("Message: " + message); // 使用 Consumer 的 accept 方法 printMessage.accept("Hello, Lambda!"); // 输出: Message: Hello, Lambda! } }
-
-
Supplier:没有参数但返回一个结果。
-
模板:
Supplier<T>
-
例子:
import java.util.function.Supplier; public class SupplierExample { public static void main(String[] args) { // 定义一个 Supplier 类型的变量,接收一个 Lambda 表达式 Supplier<Double> randomValue = () -> Math.random(); // 使用 Supplier 的 get 方法 System.out.println(randomValue.get()); // 输出: 随机数 } }
-
-
Predicate:接收一个参数并返回一个布尔值。
-
模板:
Predicate<T>
-
例子:
import java.util.function.Predicate; public class PredicateExample { public static void main(String[] args) { // 定义一个 Predicate 类型的变量,接收一个 Lambda 表达式 Predicate<Integer> isEven = number -> number % 2 == 0; // 使用 Predicate 的 test 方法 System.out.println(isEven.test(4)); // 输出: true System.out.println(isEven.test(5)); // 输出: false } }
-
-
BiFunction:接收两个参数并返回一个结果。
-
模板:
BiFunction<T, U, R>
-
例子:
import java.util.function.BiFunction; public class BiFunctionExample { public static void main(String[] args) { // 定义一个 BiFunction 类型的变量,接收两个整数并返回它们的和 BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; // 使用 BiFunction 的 apply 方法 System.out.println(add.apply(3, 5)); // 输出: 8 } }
-
三、Lambda的基础语法
public class UseSimpleInterface {
public static void main(String[] args) {
SimpleInterface obj = () -> System.out.println("this is a lambda example");
obj.doSomething();
SimpleInterface obj2 = () -> {
System.out.println("Hello");
System.out.println("world");
};
obj2.doSomething();
}
}
@FunctionalInterface
interface SimpleInterface {
void doSomething();
}
public class UseInterfaceWithArgs {
public static void main(String[] args) {
InterfaceWithArgs obj = (v1, v2) -> {
int result = v1 + v2;
System.out.println("The result is " + result);
};
obj.doSomething(100, 200);
}
}
interface InterfaceWithArgs {
void doSomething(int value1, int value2);
}
Lambda表达式生成的接口可以访问接口自定义的局部变量,可以访问它所在的方法定义的局部变量,可以访问类的实例变量,还可以访问它所在的方法的参数。
public class VisitVariableTest {
private final int counter = 100;
public static void main(String[] args) {
VisitVariableTest obj = new VisitVariableTest();
obj.test("hello");
}
private void test(String info) {
String methodMsg = "test方法中定义的methodMsg变量";
Printer printer = localMsg -> {
System.out.println("Lambda可以访问自己定义的局部变量:msg=" + localMsg);
System.out.println("Lambda还可以访问它所在方法所定义的局部变量:methodMsg=" + methodMsg);
System.out.println("Lambda也能访问类的实例变量:counter=" + counter);
System.out.println("Lambda还可以访问方法的参数:info="+info);
};
printer.print("Hello,World.");
}
}
@FunctionalInterface
interface Printer {
void print(String msg);
}
四、Lambda排序的实例
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class UseComparator {
public static void main(String args[]) {
List<String> strings = new ArrayList<String>();
strings.add("AAA");
strings.add("bbb");
strings.add("CCC");
strings.add("ddd");
strings.add("EEE");
//使用Lambda表达式重写上述代码段
Comparator<String> comparator = (str1, str2) -> {
return str1.compareToIgnoreCase(str2);
};
Collections.sort(strings, comparator);
System.out.println("Sort with comparator");
//输出排序结果
for (String str : strings) {
System.out.println(str);
}
}
}
像在这里,Comparator就是一个函数接口有两个形参,一个输出,就是利用Lambda里面传入两个形参s1,s2,然后利用List<string>自带的compareToIgnoreCase(str2)。 return一个整型来作为排序的标准的比较函数。