feat(class39): 添加 Lambda表达式示例代码
- 新增 LambdaDemo1.java 文件,演示函数式接口和 Lambda 表达式的使用 - 新增 LambdaDemo2.java 文件,展示 Lambda表达式在数组排序和事件监听中的应用 - 通过具体实例说明 Lambda 表达式的简洁性和高效性
This commit is contained in:
31
src/class39/LambdaDemo1.java
Normal file
31
src/class39/LambdaDemo1.java
Normal file
@@ -0,0 +1,31 @@
|
||||
package class39;
|
||||
|
||||
public class LambdaDemo1 {
|
||||
public static void main(String[] args) {
|
||||
Animal a = new Animal() {
|
||||
@Override
|
||||
public void cry() {
|
||||
System.out.println("cry...");
|
||||
}
|
||||
};
|
||||
a.cry();
|
||||
// Swim s1 = new Swim() {
|
||||
// @Override
|
||||
// public void swimming() {
|
||||
// System.out.println("student is swimming...");
|
||||
// }
|
||||
// };
|
||||
|
||||
Swim s1 = () -> System.out.println("student is swimming...");//lambda表达式,函数式接口的实现
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Animal{
|
||||
public abstract void cry();
|
||||
}
|
||||
//函数式接口:有且只有一个抽象方法
|
||||
@FunctionalInterface //声明函数式接口的注解
|
||||
interface Swim{
|
||||
void swimming();
|
||||
}
|
||||
42
src/class39/LambdaDemo2.java
Normal file
42
src/class39/LambdaDemo2.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package class39;
|
||||
|
||||
import class38.Student;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class LambdaDemo2 {
|
||||
public static void main(String[] args) {
|
||||
test2();
|
||||
}
|
||||
public static void test1(){
|
||||
Student[] students = new Student[6];
|
||||
students[0] = new Student("般素素", 35, 171.5, '女');
|
||||
students[1] = new Student("杨幂", 28, 168.5, '女');
|
||||
students[2] = new Student("张无忌", 25, 181.5, '男');
|
||||
students[3] = new Student("小昭", 19, 165.5, '女');
|
||||
students[4] = new Student("赵敏", 27, 167.5, '女');
|
||||
students[5] = new Student("刘亦菲", 36, 168, '女');
|
||||
//IDEA提示简化
|
||||
// Arrays.sort(students, Comparator.comparingInt(Student::getAge));
|
||||
Arrays.sort(students, (o1, o2) -> o1.getAge() - o2.getAge());
|
||||
|
||||
for (Student student : students) {
|
||||
System.out.println(student);
|
||||
}
|
||||
}
|
||||
public static void test2(){
|
||||
JFrame win = new JFrame("登陆窗口");
|
||||
win.setSize(300,200);
|
||||
win.setLocationRelativeTo(null);
|
||||
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
win.setVisible(true);
|
||||
JPanel panel = new JPanel();
|
||||
win.add(panel);
|
||||
JButton btn = new JButton("登陆");
|
||||
btn.addActionListener(e -> System.out.println("点击了登陆按钮"));
|
||||
panel.add(btn);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user