Java Lambda示例
Lambda表達式 —— 用簡單的方法實現只有一個函數的接口
Lambda syntax
|
1
2
3
|
(parameters) -> expression
(parameters) -> statement
(parameters) -> { statements }
|
Lambda表達式實例
|
1
2
3
|
(intx,inty) -> x + y
() -> System.out.println("hi "+ s);
(String s) -> {intn = s.length();returnn; }
|
運行Runnable
|
1
2
|
Runnable r = () -> System.out.println("Hello!");
r.run();
|
PI函數
|
1
2
|
Callable<Double> pi = () ->3.14;
Double p = pi.call();
|
根據字符串長度來排序字符串
|
1
2
3
4
5
|
String[] words = {"aaa","b","cc"};
Arrays.sort(words, (s1, s2) -> s1.length() - s2.length());
// 等價于:
Arrays.sort(words, (String s1, String s2) -> s1.length() - s2.length());
|
高效的final變量可以在lambdas中被引用
|
1
2
3
4
5
|
// s是高效的final變量(不會更改)
String s ="foo";
// s可以在lambdas中被引用
Runnable r = () -> System.out.println(s);
|
方法引用 —— 用函數的方法使用現有方法
靜態方法引用
|
1
2
3
4
5
|
// Class::staticMethod syntax
Arrays.sort(items, Util::compareItems);
// 等價于:
Arrays.sort(items, (a, b) -> Util.compareItems(a, b));
|
實例方法引用
|
1
2
3
4
5
|
// instance::instanceMethod syntax
items.forEach(System.out::print);
// 等價于:
items.forEach((x) -> System.out.print(x));
|
對任意實例的方法的引用
|
1
2
3
4
5
|
// Class::instanceMethod syntax
items.forEach(Item::publish);
// 等價于:
items.forEach((x) -> { x.publish(); });
|
構造器引用
|
1
2
|
ConstructorReference cref = Item::new;
Item item = cref.constructor();
|
Default方法 —— 接口的方法進行默認的實現
在接口中定義默認的default方法
|
1
2
3
4
5
6
7
|
interfaceDescriptive {
defaultString desc() {
return"fantastic";
}
}
|
實現包含default方法的接口
|
1
2
3
4
5
6
|
classItemimplementsDescriptive { }
Item x =newItem();
// prints "fantastic"
System.out.println(x.desc());
|
Stream – 值的序列
對非空字符進行計數
|
1
2
|
List<String> strings = ...;
longn = strings.stream().filter(x -> !x.isEmpty()).count();
|
連接元素的title
|
1
2
|
List<Item> items = ...;
String names = items.stream().map((x) -> x.getTitle()).collect(Collectors.joining(", "));
|
由‘城市’列表獲得唯一的‘國家’列表
|
1
2
|
List<City> cities = ...;
List<Country> countries = cities.stream().map((c) -> c.getCountry()).distinct().collect(Collectors.toList());
|
獲得元素rating的計數、最小值、最大值、總數、平均值等統計數據
|
1
2
|
List<Item> items = ...;
IntSummaryStatistics stats = items.stream().mapToInt((x) -> x.getRating()).summaryStatistics();
|
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!