1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.Comparator; 4 import java.util.List; 5 6 /** 7 * JAVA8 Lambda基础用法测试 8 * 9 * @author yangzhilong 10 * 11 */ 12 public class LambdaTest { 13 14 public static void main(String[] args) { 15 test1(); 16 test2(); 17 } 18 19 private static void test1(){ 20 //传统写法 21 new Thread(new Runnable() { 22 23 @Override 24 public void run() { 25 System.out.print("这是传统的输出:"); 26 System.out.println("111111111111111"); 27 28 } 29 }).start(); 30 31 //Lambda写法 32 new Thread(() -> { 33 System.out.print("这是Lambda的输出:"); 34 System.out.println("22222222222222"); 35 }).start();; 36 } 37 38 private static void test2(){ 39 List<Integer> list = new ArrayList<>(); 40 list.add(5); 41 list.add(9); 42 list.add(3); 43 list.add(11); 44 45 //传统写法 46 Collections.sort(list, new Comparator<Integer>() { 47 @Override 48 public int compare(Integer o1, Integer o2) { 49 return o1.compareTo(o2); 50 } 51 }); 52 print(list); 53 54 //Lambda写法 55 Collections.sort(list, (o1, o2) -> o2.compareTo(o1)); 56 57 print(list); 58 } 59 60 private static void print(List<Integer> list){ 61 for (Integer integer : list) { 62 System.out.print(integer + " "); 63 } 64 System.out.println(""); 65 } 66 }
输出结果:
这是传统的输出:111111111111111
这是Lambda的输出:22222222222222
3 5 9 11
11 9 5 3