标签:
#JDK8 Lambdas 基础入门(一)
jdk8 重要的一个新特性就是lambdas
详细概念我就不一一介绍了,详细的请查看[lambdas](http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html#overview)
小栗子认识一下lambda 函数编程:
```java
public class LambdasTest {
public static void main(String[] args) {
List<String> names = Arrays.asList("palmg", "kai", "shui");
//按照字符的长度排序
Collections.sort(names, (first, second) -> first.length() - second.length());
//打印每个字符
names.forEach(System.out::println);
}
}
```
##详lambdas的使用
###1. 匿名函数 VS lambdas
```java
public class LambdasTest01 {
interface Message {
void send(Runnable runnable);
}
static class PhoneMessage implements Message {
private AtomicInteger num = new AtomicInteger(0);
@Override
public void send(Runnable runnable) {
runnable.run();
System.out.println("--------------我是分界线" + (num.getAndIncrement()) + "-----------------");
}
}
public static void main(String[] args) {
PhoneMessage phoneMessage = new PhoneMessage();
//1. jdk 8 之前我们需要实现一个匿名函数
phoneMessage.send(new Runnable() {
@Override
public void run() {
System.out.println("匿名函数写法");
}
});
//2. jkd8之后,我们可以这样
phoneMessage.send(() -> System.out.println("lambdas表达方式"));
}
}
```
执行结果:
```java
匿名函数写法
--------------我是分界线0-----------------
lambdas表达方式
--------------我是分界线1-----------------
```
###2. 集合排序 vs lambdas
```java
/**
* Lambdas Comparator
* Created by Kaishui on 2016/8/30.
*/
public class LambdasTest02 {
static class NameComparator implements Comparator<String> {
@Override
public int compare(String first, String second) {
return first.compareTo(second);
}
}
public static void main(String[] args) {
List<String> names = Arrays.asList("palmg", "kai", "shui");
System.out.println("1.方法一: jdk8之前,按照名称排序");
Collections.sort(names, new NameComparator());
for (String name : names) { //打印
System.out.println(name);
}
System.out.println("2.方法二: dk8之前,按照名称排序");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String first, String second) {
return first.compareTo(second);
}
});
for (String name : names) { //打印
System.out.println(name);
}
System.out.println("---------我只是一条分割线-------------");
System.out.println("3. jdk8 lamdas");
Collections.sort(names, (first, second) -> first.compareTo(second));
names.forEach(System.out::println);
}
}
```
上述两个例子看到不仅仅是一个代码量的差距,lambdas写得还是很优美的。
下一篇将介绍:Predicate、Consumer、Function、Supplier
标签:
原文地址:http://www.cnblogs.com/kaishuinan/p/a63d409db8378147f4c7f2142ef3b33e.html