Lambda 函数式编程








1 public interface Cook { 2 void makeFood(); 3 } 4 5 6 public class CookLambda { 7 public static void main(String[] args) { 8 invoke(new Cook() { 9 @Override 10 public void makeFood() { 11 System.out.println("noodles"); 12 } 13 }); 14 15 invoke(() -> System.out.println("rices")); 16 } 17 18 private static void invoke(Cook cook) { 19 cook.makeFood(); 20 } 21 }


1 public interface Calculator { 2 public abstract int calc(int a , int b); 3 } 4 5 6 public class MinLambdaDemo { 7 public static void main(String[] args) { 8 invokeCalc(10, 30, new Calculator() { 9 @Override 10 public int calc(int a, int b) { 11 return a + b; 12 } 13 }); 14 15 invokeCalc(15, 28, (a, b) -> a + b); 16 } 17 18 private static void invokeCalc(int a, int b, Calculator calculator) { 19 int sum = calculator.calc(a, b); 20 System.out.println(sum); 21 } 22 }
1 public class Student { 2 private String studentName; 3 private int studentAge; 4 5 public String getStudentName() { 6 return studentName; 7 } 8 9 public void setStudentName(String studentName) { 10 this.studentName = studentName; 11 } 12 13 public int getStudentAge() { 14 return studentAge; 15 } 16 17 public void setStudentAge(int studentAge) { 18 this.studentAge = studentAge; 19 } 20 21 public Student() { 22 } 23 24 public Student(String studentName, int studentAge) { 25 this.studentName = studentName; 26 this.studentAge = studentAge; 27 } 28 29 @Override 30 public String toString() { 31 return "Student{" + 32 "studentName='" + studentName + '\'' + 33 ", studentAge=" + studentAge + 34 '}'; 35 } 36 } 37 38 39 public class ArraysSortLambda { 40 public static void main(String[] args) { 41 Student[] students = { 42 new Student("jim", 15), 43 new Student("lily", 13), 44 new Student("mary", 18) 45 }; 46 // Arrays.sort(students, new Comparator<Student>() { 47 // @Override 48 // public int compare(Student o1, Student o2) { 49 // return o1.getStudentAge() - o2.getStudentAge(); 50 // } 51 // }); 52 53 Arrays.sort(students, (o1, o2) -> o2.getStudentAge() - o1.getStudentAge()); 54 55 // System.out.println(Arrays.toString(students)); 56 for (Student student : students) { 57 System.out.println(student); 58 } 59 } 60 }

浙公网安备 33010602011771号