Java 8

1.背景

按照 Java 的发布计划,Java 12 将于2019年 3 月推出,本人现在还在使用Java 8,这本身没有什么问题,但“惭愧”的是目前不会使用8的新特性。

“这段代码中,使用了Java 8 的LAMBDA表达式”。

“一会让你见识见识Java 8 的STREAM有多好用”。

每当听到或看到,类似以上内容的话语或文字的时候,发出感慨者那种优于其它人的自豪感,让我更加的“惭愧”。

2.代码

LAMBDA

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class test {
public static void main(String[] args) {
// 不用LAMBDA
MathOperation mathOperation = new MathOperation() {
@Override
public int operation(int a, int b) {
return a + b;
}
};
System.out.println(new test().operate(100, 50, mathOperation));

// 用LAMBDA
System.out.println(new test().operate(100, 50, (a, b) -> a + b));
}

interface MathOperation {
int operation(int a, int b);
}

private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
}

STREAM

Set;List;Map;SortedSet;SortedMap;HashSet;TreeSet;ArrayList;LinkedList;Vector;Collections;Arrays;AbstractCollection
以上这些类都有stream()方法,这就是传说中的STREAM。

  • filter 方法用于通过设置的条件过滤出元素。
  • sorted 方法用于对流进行排序。
  • map 方法用于映射每个元素到对应的结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class test {
public static void main(String[] args) {
List<String> rStrings;
List<String> strings = Arrays.asList("a", "ab", "ac", "d", "e", "f", "ag");
System.out.println("stream filter:");
rStrings = strings.stream().filter(string -> string.contains("a")).collect(Collectors.toList());
System.out.println(rStrings.toString());
System.out.println("stream sorted:");
rStrings = strings.stream().sorted().collect(Collectors.toList());
System.out.println(rStrings.toString());
System.out.println("stream map:");
rStrings = strings.stream().map(string -> string + string).collect(Collectors.toList());
System.out.println(rStrings.toString());
}
}

Console

1
2
3
4
5
6
stream filter:
[a, ab, ac, ag]
stream sorted:
[a, ab, ac, ag, d, e, f]
stream map:
[aa, abab, acac, dd, ee, ff, agag]

3.总结

代码变简洁了,可读性和调试变得不方便了。

4.名人名言

有的人滥用形容词语和形容句子,以为堆砌得越多越漂亮;有的人不肯顺着一般人的表达习惯来写,以为不说些离奇别扭的话就不成其为文章;有的人搬弄一些俗滥的成语或者典故,以为不这样做不足以显示自己的高明。—叶圣陶

有真意,去粉饰,少做作,勿卖弄。—鲁迅