
前期回顾:
JDK1.8新特性(一):JDK1.8究竟有哪些新特性呢
JDK1.8新特性(二):为什么要关注JDK1.8
JDK1.8新特性(三):Lambda表达式,让你爱不释手
JDK1.8新特性(四):函数式接口
JDK1.8新特性(五):Stream,集合操作利器,让你好用到飞起来
上一篇JDK1.8新特性(五):Stream,集合操作利器,让你好用到飞起来,主要讲解了关于Stream的基本操作,可以轻松摆脱"遍历、再遍历、再运算"等复杂操作,但Stream远远不止这些。本文将讲述关于Stream的终极操作,让你轻松解决集合的分组、汇总等操作,让其他同事对你刮目相看。
一、Collectors
java.util.stream.Collectors,是从JDK1.8开始新引入的一个类。从源码的类注释上,我们可以知道:Collectors实现了各种有用归约的操作,例如类型归类到新集合、根据不同标准汇总元素等。透过示例,能让我们眼前一亮,短短的一行代码却能处理如此强大、复杂的功能:汇总、拼接、累加计算、分组等。
切记,不要用错哦,是java.util.stream.Collectors,不是java.util.Collections。
/*** Implementations of {@link Collector} that implement various useful reduction* operations, such as accumulating elements into collections, summarizing* elements according to various criteria, etc.**
The following are examples of using the predefined collectors to perform* common mutable reduction tasks:**
{@code* // Accumulate names into a List* List list = people.stream().map(Person::getName).collect(Collectors.toList());** // Accumulate names into a TreeSet* Set set = people.stream().map(Person::getName).collect(Collectors.toCo