点赞再看,养成习惯,大家好,我是辰兮!今天介绍Function.identity()的使用。
一、介绍
Stream流大家应该都不陌生,可以方便日常开发,今天介绍在使用Stream时,需要转换为其他容器或者Map类型,这时候就会用到Function.identity()。
Map<String, ProductionNodeVO> nodeMap = nodes.stream()
.collect(toMap(ProductionNodeVO::getCode, Function.identity()));
Function
是interface接口,那么Function.identity()
是干什么的呢?
identity()其实
就是Function
接口的一个静态方法,等价于形如t -> t
形式的Lambda表达式。
看源码:
static <T> Function<T, T> identity() {
return t -> t;
}
二、使用步骤
如果需要对人员信息进行分组则:
Map<String, PersonInfo> personIdMap = personInfos.stream()
.collect(toMap(PersonInfo::getPersonId, Function.identity()));
总结
Function.identity()的实现其实就是等价于形如t -> t
形式的Lambda表达式。
可以让代码更加优雅化。
最后:
我是辰兮,不开心就笑一笑,世界没有那么糟,咱们下期见!
靓仔们的 【三连】 就是辰兮创作的最大动力,如果本篇博客有任何错误和建议,欢迎靓仔们留言!