Java8新特性 - Lambda表达式 - 基本知识
A lambda expression is an unnamed block of code (or an unnamed function) with a list of formal parameters and a
body.
Java8中的lambda表达式不同于C#,使用的是->
eg:
// Takes an int parameter and returns the parameter value incremented by 1 (int x) -> x + 1 // Takes two int parameters and returns their sum (int x, int y) -> x + y // Takes two int parameters and returns the maximum of the two (int x, int y) -> { int max = x > y ? x : y; return max; } // Takes no parameters and returns void () -> { } // Takes no parameters and returns a string "OK" () -> "OK" // Takes a String parameter and prints it on the standard output (String msg) -> { System.out.println(msg); } // Takes a parameter and prints it on the standard output msg -> System.out.println(msg) // Takes a String parameter and returns its length (String str) -> str.length()
下面看一个简单的例子
Adder.java
package corejava2.lambda; @FunctionalInterface public interface Adder { double add(double n1, double n2); }
Joiner.java
package corejava2.lambda; @FunctionalInterface public interface Joiner { String join(String s1, String s2); }
TargetTypeTest.java
package corejava2.lambda; public class TargetTypeTest { public static void main(String[] args) { // Creates an Adder using a lambda expression Adder adder = (x, y) -> x + y; // Creates a Joiner using a lambda expression Joiner joiner = (x, y) -> x + y; // Adds two doubles double sum1 = adder.add(10.34, 89.11); // Adds two ints double sum2 = adder.add(10, 89); // Joins two strings String str = joiner.join("Hello", " lambda"); System.out.println("sum1 = " + sum1); System.out.println("sum2 = " + sum2); System.out.println("str = " + str); } }
运行结果:
sum1 = 99.45
sum2 = 99.0
str = Hello lambda
技术改变世界