This seems reasonable; mapping() already exists for use in this space
(as a combinator for the downstream collector of groupingBy and
friends), filtering() is also reasonable in this context.
On 12/4/2015 3:53 PM, ShinyaYoshida wrote:
Thank you for your comment.
2015-12-05 3:28 GMT+09:00 Henry Jen <[email protected]
<mailto:[email protected]>>:
My first thought is what’s wrong with
stream.filter(predicate).collect(...)?
In your case, that would be,
amps.stream().filter(e -> e.getSalary() > 2000)
.collect(groupingBy(Employee::getDepartment), Collectors.counting())
That should work just fine?
Unfortunately, not, Stream#filter could not satisfy us in this case.
Because when I filter before collecting, the entry which the value is
0 will not be appeared in the result map.
Ex)
filtering collector(Collectors#filtering): http://ideone.com/83Lzb7
filtering before collecting(Stream#filter): http://ideone.com/EmTrXE
Regards,
shinyafox(ShinyaYoshida)
Cheers,
Henry
> On Dec 3, 2015, at 10:57 PM, ShinyaYoshida <[email protected]
<mailto:[email protected]>> wrote:
>
> Hi, core-libs-dev and Brian, Paul,
> I'd like to propose adding filtering method to Collectors.
>
> When I consider the operation what is "grouping the number of
employees
> whose income is over 2000 by the depertment from employees", we
have to
> write following because there is no way to filter for Collector:
> (Note: In this case, we need the entry which the value is 0)
>
> Map<Department, Long> map = emps.stream()
> .collect(groupingBy(Employee::getDepartment,
> collectingAndThen(toList(),
> es -> es.stream().filter(e -> e.getSalary() >
2000).count())));
>
> When I add filtering like following to Collectors, we can write
it easy,
> and it would be more efficient.
> public static <T, A, R>
> Collector<T, ?, R> filtering(Predicate<? super T> filter,
> Collector<? super T, A, R>
downstream) {
> BiConsumer<A, ? super T> downstreamAccumulator =
> downstream.accumulator();
> return new CollectorImpl<>(downstream.supplier(),
> (r, t) -> {
> if (filter.test(t)) {
> downstreamAccumulator.accept(r,
> t);
> }
> },
> downstream.combiner(),
> downstream.finisher(),
> downstream.characteristics());
> }
>
> Map<Department, Long> map = emps.stream()
> .collect(groupingBy(Employee::getDepartment,
> filtering(e -> e.getSalary() > 2000, counting())));
>
> Here is patch:
> webrev: http://cr.openjdk.java.net/~shinyafox/8144675/webrev.00/
<http://cr.openjdk.java.net/%7Eshinyafox/8144675/webrev.00/>
> bugs: https://bugs.openjdk.java.net/browse/JDK-8144675
>
> Could you consider this patch and proposal?
>
> Regards,
> shinyafox(Shinya Yoshida)