无参Lambda表达式详解
·
// Listing 1: 无参Lambda表达式
interface MyNumber {
double getValue();
}
class LambdaDemo {
public static void main(String args[]) {
MyNumber myNum;
myNum = () -> 123.45; //无参Lambda表达式,返回常量 System.out.println("A fixed value: " + myNum.getValue());
myNum = () -> Math.random() * 100; //无参Lambda表达式,返回随机数 System.out.println("A random value: " + myNum.getValue());
System.out.println("Another random value: " + myNum.getValue());
}
}
输出:
A fixed value: 123.45
A random value: <随机数>
Another random value: <另一个随机数>
// Listing 2: 单参数Lambda表达式
interface NumericTest {
boolean test(int n);
}
class LambdaDemo2 {
public static void main(String args[]) {
NumericTest isEven = (n) -> (n % 2) == 0; // 单参数Lambda,判断偶数
if (isEven.test(10)) System.out.println("10 is even");
if (!isEven.test(9)) System.out.println("9 is not even");
NumericTest isNonNeg = (n) -> n >= 0; // 单参数Lambda,判断非负数
if (isNonNeg.test(1)) System.out.println("1 is non-negative");
if (!isNonNeg.test(-1)) System.out.println("-1 is negative");
}
}
输出:
10 is even
9 is not even
1 is non-negative
-1 is negative
// Listing 3: 多参数Lambda表达式
interface NumericTest2 {
boolean test(int n, int d);
}
class LambdaDemo3 {
public static void main(String args[]) {
NumericTest2 isFactor = (n, d) -> (n % d) == 0; // 双参数Lambda,判断因子 if (isFactor.test(10, 2))
System.out.println("2 is a factor of 10");
if (!isFactor.test(10, 3))
System.out.println("3 is not a factor of 10");
}
}
输出:
2 is a factor of 10
3 is not a factor of 10
// Listing 4: 块Lambda表达式(计算阶乘)
interface NumericFunc {
int func(int n);
}
class BlockLambdaDemo {
public static void main(String args[]) {
NumericFunc factorial = (n) -> { // 块Lambda,包含多条语句
int result = 1;
for (int i = 1; i <= n; i++)
result = i * result;
return result; // 必须显式返回
};
System.out.println("The factorial of 3 is " + factorial.func(3));
System.out.println("The factorial of 5 is " + factorial.func(5));
}
}
输出:
The factorial of 3 is 6
The factorial of 5 is 120
// Listing 5: 块Lambda表达式(字符串反转)
interface StringFunc {
String func(String n);
}
class BlockLambdaDemo2 {
public static void main(String args[]) {
StringFunc reverse = (str) -> {
String result = "";
for (int i = str.length()1; i >= 0; i--)
result += str.charAt(i);
return result;
};
System.out.println("Lambda reversed is " + reverse.func("Lambda"));
System.out.println("Expression reversed is " + reverse.func("Expression"));
}
}
输出:
Lambda reversed is adbmaL
Expression reversed is noisserpxE
// Listing 6: 泛型函数式接口
interface SomeFunc<T> {
T func(T t);
}
class GenericFunctionalInterfaceDemo {
public static void main(String args[]) {
SomeFunc<String> reverse = (str) -> { // 泛型接口的字符串版本
String result = "";
for (int i = str.length()1; i >= 0; i--)
result += str.charAt(i);
return result;
};
System.out.println("Lambda reversed is " + reverse.func("Lambda"));
System.out.println("Expression reversed is " + reverse.func("Expression"));
SomeFunc<Integer> factorial = (n) -> { // 泛型接口的整数版本
int result = 1;
for (int i = 1; i <= n; i++)
result = i * result;
return result;
};
System.out.println("The factorial of 3 is " + factorial.func(3));
System.out.println("The factorial of 5 is " + factorial.func(5));
}
}
输出:
Lambda reversed is adbmaL
Expression reversed is noisserpxE
The factorial of 3 is 6
The factorial of 5 is 120
// Listing 7: Lambda表达式作为方法参数
interface StringFunc {
String func(String n);
}
class LambdasAsArgumentsDemo {
static String stringOp(StringFunc sf, String s) {
return sf.func(s);
}
public static void main(String args[]) {
String inStr = "Lambdas add power to Java";
String outStr;
outStr = stringOp((str) -> str.toUpperCase(), inStr); // Lambda作为参数传递
System.out.println("The string in uppercase: " + outStr);
outStr = stringOp((str) -> { // 块Lambda作为参数传递
String result = "";
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) != ' ')
result += str.charAt(i);
return result;
}, inStr);
System.out.println("The string with spaces removed: " + outStr);
StringFunc reverse = (str) -> { // 先定义Lambda表达式 String result = "";
for (int i = str.length() - 1; i >= 0; i--)
result += str.charAt(i);
return result;
};
System.out.println("The string reversed: " + stringOp(reverse, inStr));
}
}
输出:
Here is input string: Lambdas add power to Java
The string in uppercase: LAMBDAS ADD POWER TO JAVA
The string with spaces removed: LambdasaddpowertoJava
The string reversed: avaJ ot rewop dda sadbmaL
// Listing 8: Lambda表达式抛出异常
interface DoubleNumericArrayFunc {
double func(double[] n) throws EmptyArrayException;
}
class EmptyArrayException extends Exception {
EmptyArrayException() {
super("Array Empty");
}
}
class LambdaExceptionDemo {
public static void main(String args[]) throws EmptyArrayException {
double[] values = {1.0, 2.0, 3.0, 4.0};
DoubleNumericArrayFunc average = (n) -> {
double sum = 0;
if (n.length == 0)
throw new EmptyArrayException(); // Lambda内抛出异常 for (int i = 0; i < n.length; i++)
sum += n[i];
return sum / n.length;
};
System.out.println("The average is " + average.func(values));
System.out.println("The average is " + average.func(new double[0])); // 触发异常
}
}
输出:
The average is 2.5
Exception in thread "main" EmptyArrayException: Array Empty
at LambdaExceptionDemo.lambda$main$0(LambdaExceptionDemo.java:...)
at LambdaExceptionDemo.main(LambdaExceptionDemo.java:...)
// Listing 9: Lambda表达式捕获局部变量
interface MyFunc {
int func(int n);
}
class VarCapture {
public static void main(String args[]) {
int num = 10; // 被捕获的局部变量,必须是final或等效final
MyFunc myLambda = (n) -> {
int v = num + n; // 可以读取局部变量
// num++; // 错误:不能修改捕获的变量 return v;
};
// num = 9; // 错误:会破坏num的等效final状态 }
}
// Listing 10: 静态方法引用
interface StringFunc {
String func(String n);
}
class MyStringOps {
static String strReverse(String str) { // 静态方法
String result = "";
for (int i = str.length()1; i >= 0; i--)
result += str.charAt(i);
return result;
}
}
class MethodRefDemo {
static String stringOp(StringFunc sf, String s) {
return sf.func(s);
}
public static void main(String args[]) {
String inStr = "Lambdas add power to Java";
String outStr;
outStr = stringOp(MyStringOps::strReverse, inStr); // 静态方法引用
System.out.println("Original string: " + inStr);
System.out.println("String reversed: " + outStr);
}
}
输出:
Original string: Lambdas add power to Java
String reversed: avaJ ot rewop dda sadbmaL
// Listing 11: 实例方法引用
interface StringFunc {
String func(String n);
}
class MyStringOps {
String strReverse(String str) { // 实例方法
String result = "";
for (int i = str.length()1; i >= 0; i--)
result += str.charAt(i);
return result;
}
}
class MethodRefDemo2 {
static String stringOp(StringFunc sf, String s) {
return sf.func(s);
}
public static void main(String args[]) {
String inStr = "Lambdas add power to Java";
String outStr;
MyStringOps strOps = new MyStringOps(); // 创建对象 outStr = stringOp(strOps::strReverse, inStr); // 实例方法引用 System.out.println("Original string: " + inStr);
System.out.println("String reversed: " + outStr);
}
}
输出:
Original string: Lambdas add power to Java
String reversed: avaJ ot rewop dda sadbmaL
// Listing 12: 特定对象的实例方法引用
interface MyFunc<T> {
boolean func(T v1, T v2);
}
class HighTemp {
private int hTemp;
HighTemp(int ht) {
hTemp = ht;
}
boolean sameTemp(HighTemp ht2) { // 实例方法
return hTemp == ht2.hTemp;
}
boolean lessThanTemp(HighTemp ht2) { // 实例方法 return hTemp < ht2.hTemp;
}
}
class InstanceMethWithObjectRefDemo {
static <T> int counter(T[] vals, MyFunc<T> f, T v) {
int count = 0;
for (int i = 0; i < vals.length; i++)
if (f.func(vals[i], v)) count++;
return count;
}
public static void main(String args[]) {
HighTemp[] weekDayHighs = {new HighTemp(89), new HighTemp(82),
new HighTemp(90), new HighTemp(89),
new HighTemp(89), new HighTemp(91),
new HighTemp(84), new HighTemp(83)};
int count = counter(weekDayHighs, HighTemp::sameTemp, new HighTemp(89));
System.out.println(count + " days had a high of 89");
HighTemp[] weekDayHighs2 = {new HighTemp(32), new HighTemp(12),
new HighTemp(24), new HighTemp(19),
new HighTemp(18), new HighTemp(12),
new HighTemp(-1), new HighTemp(13)};
count = counter(weekDayHighs2, HighTemp::sameTemp, new HighTemp(12));
System.out.println(count + " days had a high of 12");
count = counter(weekDayHighs, HighTemp::lessThanTemp, new HighTemp(89));
System.out.println(count + " days had a high less than 89");
count = counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19));
System.out.println(count + " days had a high of less than 19");
}
}
输出:
3 days had a high of 89
2 days had a high of 12
5 days had a high less than 89
3 days had a high of less than 19
// Listing 13: 泛型方法引用
interface MyFunc<T> {
int func(T[] vals, T v);
}
class MyArrayOps {
static <T> int countMatching(T[] vals, T v) { // 泛型静态方法 int count = 0;
for (int i = 0; i < vals.length; i++)
if (vals[i] == v) count++;
return count;
}
}
class GenericMethodRefDemo {
static <T> int myOp(MyFunc<T> f, T[] vals, T v) {
return f.func(vals, v);
}
public static void main(String args[]) {
Integer[] vals = {1, 2, 3, 4, 2, 3, 4, 4, 5};
String[] strs = {"One", "Two", "Three", "Two"};
int count;
count = myOp(MyArrayOps::<Integer>countMatching, vals, 4); // 泛型方法引用 System.out.println("vals contains " + count + " 4s");
count = myOp(MyArrayOps::<String>countMatching, strs, "Two");
System.out.println("strs contains " + count + " Twos");
}
}
输出:
vals contains 3 4s
strs contains 2 Twos
// Listing 14: 方法引用与集合操作
import java.util.*;
class MyClass {
private int val;
MyClass(int v) {
val = v;
}
int getVal() {
return val;
}
}
class UseMethodRef {
static int compareMC(MyClass a, MyClass b) { // 静态比较方法
return a.getVal() - b.getVal();
}
public static void main(String args[]) {
ArrayList<MyClass> al = new ArrayList<MyClass>();
al.add(new MyClass(1));
al.add(new MyClass(4));
al.add(new MyClass(2));
al.add(new MyClass(9));
al.add(new MyClass(3));
al.add(new MyClass(7));
MyClass maxValObj = Collections.max(al, UseMethodRef::compareMC); // 方法引用作为比较器
System.out.println("Maximum value is: " + maxValObj.getVal());
}
}
输出:
Maximum value is: 9
// Listing 15: 构造器引用
interface MyFunc {
MyClass func(int n);
}
class MyClass {
private int val;
MyClass(int v) {
val = v;
}
MyClass() {
val = 0;
}
int getVal() {
return val;
}
}
class ConstructorRefDemo {
public static void main(String args[]) {
MyFunc myClassCons = MyClass::new; // 构造器引用 MyClass mc = myClassCons.func(100); // 调用func()相当于调用new MyClass(100)
System.out.println("val in mc is " + mc.getVal());
}
}
输出:
val in mc is 100
// Listing 16: 泛型类的构造器引用
interface MyFunc<T> {
MyClass<T> func(T n);
}
class MyClass<T> {
private T val;
MyClass(T v) {
val = v;
}
MyClass() {
val = null;
}
T getVal() {
return val;
}
}
class ConstructorRefDemo2 {
public static void main(String args[]) {
MyFunc<Integer> myClassCons = MyClass<Integer>::new; // 泛型构造器引用
MyClass<Integer> mc = myClassCons.func(100);
System.out.println("val in mc is " + mc.getVal());
}
}
输出:
val in mc is 100
// Listing 17: 构造器引用实现工厂模式
interface MyFunc<R, T> {
R func(T n);
}
class MyClass<T> {
private T val;
MyClass(T v) {
val = v;
}
MyClass() {
val = null;
}
T getVal() {
return val;
}
}
class MyClass2 {
String str;
MyClass2(String s) {
str = s;
}
MyClass2() {
str = "";
}
String getVal() {
return str;
}
}
class ConstructorRefDemo3 {
static <R, T> R myClassFactory(MyFunc<R, T> cons, T v) { // 工厂方法 return cons.func(v);
}
public static void main(String args[]) {
MyFunc<MyClass<Double>, Double> myClassCons = MyClass<Double>::new;
MyClass<Double> mc = myClassFactory(myClassCons, 100.1);
System.out.println("val in mc is " + mc.getVal());
MyFunc<MyClass2, String> myClassCons2 = MyClass2::new;
MyClass2 mc2 = myClassFactory(myClassCons2, "Lambda");
System.out.println("str in mc2 is " + mc2.getVal());
}
}
输出:
val in mc is 100.1
str in mc2 is Lambda
// Listing 18: 使用内置函数式接口Function
import java.util.function.Function;
class UseFunctionInterfaceDemo {
public static void main(String args[]) {
Function<Integer, Integer> factorial = (n) -> { // 使用java.util.function.Function接口 int result = 1;
for (int i = 1; i <= n; i++)
result = i * result;
return result;
};
System.out.println("The factorial of 3 is " + factorial.apply(3));
System.out.println("The factorial of 5 is " + factorial.apply(5));
}
}
输出:
The factorial of 3 is 6
The factorial of 5 is 120
参考来源
- Java 8 Lambda表达式和Lambda语法的详细解释和示例代码
- lambda表达式使用
- Java函数式编程和Lambda表达式
- Java中Lambda表达式中“->“
- Java中的Lambda表达式学习与应用
更多推荐


所有评论(0)