Lambda表达式的使用
import org.testng.annotations.Test; import java.util.Comparator; import java.util.function.Consumer; public class LambdaDemo { /** * 没有参数,没有返回值的lambda表达式 * 表达式本质上还是接口的对象 */ @Test public void test1() { Runnable runnable = new Runnable() { @Override public void run() { System.out.println("没有参数和返回值"); } }; runnable.run(); System.out.println("---------------------------------"); Runnable runnable1 = () -> { System.out.println("没有参数和返回值1"); }; runnable1.run(); } /** * 有一个参数,没有返回值 */ @Test public void test2() { Consumer<String> consumer = new Consumer<String>() { @Override public void accept(String s) { System.out.println("有一个参数是" + s); } }; consumer.accept("demo"); System.out.println("============================"); Consumer<String> consumer1 = (String s) -> { System.out.println("有一个参数是2222 " + s); }; consumer1.accept("111"); } /** * 可以省略参数类型(类型推断),如果只有一个参数,那么参数的括号可以省略 */ @Test public void test3() { Consumer<String> consumer = new Consumer<String>() { @Override public void accept(String s) { System.out.println("有一个参数是" + s); } }; consumer.accept("demo"); System.out.println("============================"); Consumer<String> consumer1 = (s) -> { System.out.println("参数的类型省略 " + s); }; consumer1.accept("111"); System.out.println("============================"); Consumer<String> consumer2 = s -> { System.out.println("参数的括号省略 " + s); }; consumer2.accept("111"); } /** * 多个参数,有返回值 */ @Test public void test4() { Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { System.out.println(o1); System.out.println(o2); return Integer.compare(o1, o2); } }; System.out.println(comparator.compare(10, 11)); System.out.println("=================================================="); Comparator<Integer> comparator1 = (o1, o2) -> { System.out.println(o1); System.out.println(o2); return Integer.compare(o1, o2); }; System.out.println(comparator1.compare(11, 10)); } /** * 函数体只有一句,可以省略return,可以省略函数体的大括号 */ @Test public void test5() { Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1, o2); } }; System.out.println(comparator.compare(10, 11)); System.out.println("=================================================="); Comparator<Integer> comparator1 = (o1, o2) -> Integer.compare(o1, o2); System.out.println(comparator1.compare(11, 10)); } }