RFR 8144675: Add a filtering collector
Tagir F. Valeev
amaembo at gmail.com
Sat Dec 5 03:31:36 UTC 2015
Hello!
Sounds reasonable. I already have such collector in my library [1].
As an alternative solution for your problem I have groupingBy
collector with domain parameter [2], so you can specify the set of
possible keys and all keys are guaranteed to be created:
Set<Department> getAllDepartmentsSet() {...}
Map<Department, Long> map = emps.stream()
.filter(e -> e.getSalary() > 2000)
.collect(MoreCollectors.groupingBy(Employee::getDepartment,
getAllDepartmentsSet(),
counting()));
With best regards,
Tagir Valeev.
[1] http://amaembo.github.io/streamex/javadoc/one/util/streamex/MoreCollectors.html#filtering-java.util.function.Predicate-java.util.stream.Collector-
[2] http://amaembo.github.io/streamex/javadoc/one/util/streamex/MoreCollectors.html#groupingBy-java.util.function.Function-java.util.Set-java.util.stream.Collector-
S> Hi, core-libs-dev and Brian, Paul,
S> I'd like to propose adding filtering method to Collectors.
S> When I consider the operation what is "grouping the number of employees
S> whose income is over 2000 by the depertment from employees", we have to
S> write following because there is no way to filter for Collector:
S> (Note: In this case, we need the entry which the value is 0)
S> Map<Department, Long> map = emps.stream()
S> .collect(groupingBy(Employee::getDepartment,
S> collectingAndThen(toList(),
S> es -> es.stream().filter(e -> e.getSalary() > 2000).count())));
S> When I add filtering like following to Collectors, we can write it easy,
S> and it would be more efficient.
S> public static <T, A, R>
S> Collector<T, ?, R> filtering(Predicate<? super T> filter,
S> Collector<? super T, A, R> downstream) {
S> BiConsumer<A, ? super T> downstreamAccumulator =
S> downstream.accumulator();
S> return new CollectorImpl<>(downstream.supplier(),
S> (r, t) -> {
S> if (filter.test(t)) {
S> downstreamAccumulator.accept(r,
S> t);
S> }
S> },
S> downstream.combiner(),
S> downstream.finisher(),
S> downstream.characteristics());
S> }
S> Map<Department, Long> map = emps.stream()
S> .collect(groupingBy(Employee::getDepartment,
S> filtering(e -> e.getSalary() > 2000, counting())));
S> Here is patch:
S> webrev: http://cr.openjdk.java.net/~shinyafox/8144675/webrev.00/
S> bugs: https://bugs.openjdk.java.net/browse/JDK-8144675
S> Could you consider this patch and proposal?
S> Regards,
S> shinyafox(Shinya Yoshida)
More information about the core-libs-dev
mailing list