java groupbyu,在Java 8中限制groupBy

How can I limit groupBy by each entry?

For example (based on this example: stream groupBy):

studentClasses.add(new StudentClass("Kumar", 101, "Intro to Web"));

studentClasses.add(new StudentClass("White", 102, "Advanced Java"));

studentClasses.add(new StudentClass("Kumar", 101, "Intro to Cobol"));

studentClasses.add(new StudentClass("White", 101, "Intro to Web"));

studentClasses.add(new StudentClass("White", 102, "Advanced Web"));

studentClasses.add(new StudentClass("Sargent", 106, "Advanced Web"));

studentClasses.add(new StudentClass("Sargent", 103, "Advanced Web"));

studentClasses.add(new StudentClass("Sargent", 104, "Advanced Web"));

studentClasses.add(new StudentClass("Sargent", 105, "Advanced Web"));

This method return simple group:

Map> groupByTeachers = studentClasses

.stream().collect(

Collectors.groupingBy(StudentClass::getTeacher));

What if I want to limit the returned collections?

Let's assume I want only the first N classes for every teacher. How can it be done?

解决方案

It would be possible to introduce a new collector that limits the number of elements in the resulting list.

This collector will retain the head elements of the list (in encounter order). The accumulator and combiner throw away every elements when the limit has been reached during collection. The combiner code is a little tricky but this has the advantage that no additional elements are added only to be thrown away later.

private static Collector> limitingList(int limit) {

return Collector.of(

ArrayList::new,

(l, e) -> { if (l.size() < limit) l.add(e); },

(l1, l2) -> {

l1.addAll(l2.subList(0, Math.min(l2.size(), Math.max(0, limit - l1.size()))));

return l1;

}

);

}

And then use it like this:

Map> groupByTeachers =

studentClasses.stream()

.collect(groupingBy(

StudentClass::getTeacher,

limitingList(2)

));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值