Java 8速查表
来源:互联网 发布:手机淘宝发货地怎么改 编辑:程序博客网 时间:2024/05/17 08:15
原文链接: Java8 翻译: ImportNew.com - 唐小娟
译文链接: http://www.importnew.com/12156.html
Lambda表达式 —— 用简单的方法实现只有一个函数的接口
Lambda syntax
1
2
3
(parameters) -> expression
(parameters) -> statement
(parameters) -> { statements }
Lambda表达式实例
1
2
3
(
int
x,
int
y) -> x + y
() -> System.out.println(
"hi "
+ s);
(String s) -> {
int
n = s.length();
return
n; }
运行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
interface
Descriptive {
default
String desc() {
return
"fantastic"
;
}
}
实现包含default方法的接口
1
2
3
4
5
6
class
Item
implements
Descriptive { }
Item x =
new
Item();
// prints "fantastic"
System.out.println(x.desc());
Stream – 值的序列
对非空字符进行计数
1
2
List<String> strings = ...;
long
n = 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();
阅读全文
0 0
- Java 8速查表
- Java 8速查表
- Java 8速查表
- java -8
- Java 8
- Java 8
- Java 8
- Java 8
- Java 8
- JAVA | 8
- Java 8: java.time.DayOfWeek
- Java 8: java.time.Month
- Java 关键字 速查表
- Java 关键字 速查表
- Java 关键字 速查表
- Java 关键字 速查表
- Java 关键字 速查表
- Java 关键字 速查表
- Android Studio中如何制作和使用.9.png(Nine Patch)图片
- Centos7 编译安装GCC 6.2.0
- Spring-注入参数详解-[通过util命名空间简化集合类型的配置]
- Rightmost Digit
- DS:Queue
- Java 8速查表
- Python数据分析-数据处理-重复值处理
- (面试题)给出一个字符串String str="12,df,45,gf,45.4,er,121"; 求其中数字的和。
- Balanced-工具类App原型分享
- CC2650/CC2640 软件不同封装问题
- redis集群服务器迁移报错[ERR] Node XXX.XXX.XXX.XX:7001 is not empty. Either the nodealready knows other nodes
- 新建MySQL数据库的注意事项
- 时间函数的用法
- VirtualBox更改虚拟磁盘大小