标签:内部类 tst 简单 ann aik btn overflow play art
使用lambda表达式能够使复杂的编写方式变的简单
(parameters) -> expression
或
(parameters) ->{ statements; }
简单的例子
(int x, int y) -> x + y //返回x+y
(String s) -> System.out.print(s) //输出s
String[] str = {"a","b","c","d"};
List<String> list = Arrays.asList(str);
for(String s:list){
System.out.println(s);
}
//lambda
list.forEach(s -> System.out.println(s));
//双冒号
list.forEach(System.out::println);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Hello world !");
}
}).start();
// 使用 lambda
new Thread(() -> System.out.println("Hello world !")).start();
Runnable race1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello world !");
}
};
// 使用 lambda表达式
Runnable race2 = () -> System.out.println("Hello world !");
// 直接调用 run 方法
race1.run();
race2.run();
// 使用匿名内部类
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
// 或者使用 lambda expression
btn.setOnAction(event -> System.out.println("Hello World!"));
String[] str = {"c","b","a","d"};
//使用匿名内部类
Arrays.sort(str, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return (s1.compareTo(s2));
}
});
//1使用lambda
Comparator<String> sortString = (String s1, String s2) -> (s1.compareTo(s2));
Arrays.sort(str, sortString);
//2使用lambda
Arrays.sort(str, (String s1, String s2) -> (s1.compareTo(s2)));
List<String> list = Arrays.asList(str);
list.forEach(s -> System.out.println(s));
标签:内部类 tst 简单 ann aik btn overflow play art
原文地址:https://www.cnblogs.com/sfencs-hcy/p/11217105.html