java8 group by example

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

public static <T,K,A,D> Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier,
                                                           Collector<? super T,A,D> downstream)

Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

The classification function maps elements to some key type K. The downstream collector operates on elements of type Tand produces a result of type D. The resulting collector produces a Map<K, D>.

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

For example, to compute the set of last names of people in each city:


     Map<City, Set<String>> namesByCity
         = people.stream().collect(groupingBy(Person::getCity,
                                              mapping(Person::getLastName, toSet())));
 

Implementation Note:

The returned Collector is not concurrent. For parallel stream pipelines, the combiner function operates by merging the keys from one map into another, which can be an expensive operation. If preservation of the order in which elements are presented to the downstream collector is not required, using groupingByConcurrent(Function, Collector) may offer better parallel performance.

Type Parameters:

T - the type of the input elements

K - the type of the keys

A - the intermediate accumulation type of the downstream collector

D - the result type of the downstream reduction

Parameters:

classifier - a classifier function mapping input elements to keys

downstream - a Collector implementing the downstream reduction

Returns:

Collector implementing the cascaded group-by operation

See Also:

groupingBy(Function)groupingBy(Function, Supplier, Collector)groupingByConcurrent(Function, Collector)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值