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<String, List<StudentClass>> 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?
This would give you the desired result, but it still categorizes all the elements of the stream:
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.
And then use it like this:
You could use collectingAndThen to define a finisher operation on the resulting list. This way you can limit, filter, sort, ... the lists:
For this you need to
.stream()
the result of your Map. You can do this by doing:This isn't a very optimal way to do it. But if you
.limit()
on the initial list, then the grouping results would be incorrect. This is the safest way to guarantee the limit.EDIT:
As stated in the comments this limits the teacher, not the class per teacher. In that case you can do: