I’ve implement a GroupingBuilder that delegates to the groupingBy factory method , What’s the problem with this fluent builder? And how i can make in effective DSL forms?
import static java.util.stream.Collectors.groupingBy; public class GroupingBuilder<T, D, K> { private final Collector<? super T, ?, Map<K, D>> collector; private GroupingBuilder(Collector<? super T, ?, Map<K, D>> collector) { this.collector = collector; } public Collector<? super T, ?, Map<K, D>> get() { return collector; } public <J> GroupingBuilder<T, Map<K, D>, J> after(Function<? super T, ? extends J> classifier) { return new GroupingBuilder<>(groupingBy(classifier, collector)); } public static <T, D, K> GroupingBuilder<T, List<T>, K> groupOn(Function<? super T, ? extends K> classifier) { return new GroupingBuilder<>(groupingBy(classifier)); } }
Advertisement
Answer
You can write in more readable format with sequence of functions defined with lambda expressions more over as you can see in below ,
Collector<? super Car, ?, Map<Brand, Map<Color, List<Car>>>> carGroupingCollector = groupOn(Car::getColor).after(Car::getBrand).get()
The use of this is counterintuitive because the grouping functions have to be written in reverse order relative to the corresponding nested grouping level. If you try to refactor this fluent builder to fix the ordering issue, you realize that unfortunately, the Java type system won’t allow you to do this.