Last active
December 8, 2015 19:28
-
-
Save gakuzzzz/250c1db02f39eaf1f622 to your computer and use it in GitHub Desktop.
Collector の直積 https://twitter.com/gakuzzzz/status/674134392449581056
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.t2v.xanadu.ds; | |
import lombok.experimental.UtilityClass; | |
import jp.t2v.xanadu.ds.Tuples.T2; | |
import java.util.function.BiFunction; | |
import java.util.stream.Collector; | |
import java.util.stream.Collector.Characteristics; | |
import java.util.stream.Stream; | |
import java.util.Set; | |
import static java.util.stream.Collector.Characteristics.CONCURRENT; | |
import static java.util.stream.Collector.Characteristics.UNORDERED; | |
@UtilityClass | |
public class Collectors { | |
public <T, A1, A2, R1, R2> Collector<T, T2<A1, A2>, T2<R1, R2>> product(Collector<? super T, A1, ? extends R1> a, Collector<? super T, A2, ? extends R2> b) { | |
return productWith(a, b, T2::of); | |
} | |
public <T, A1, A2, R1, R2, C> Collector<T, T2<A1, A2>, C> productWith(Collector<? super T, A1, ? extends R1> a, Collector<? super T, A2, ? extends R2> b, BiFunction<? super R1, ? super R2, ? extends C> f) { | |
Set<Characteristics> cs1 = a.characteristics(); | |
Set<Characteristics> cs2 = b.characteristics(); | |
return Collector.of( | |
() -> T2.of(a.supplier().get(), b.supplier().get()), | |
(acc, t) -> { | |
a.accumulator().accept(acc._1, t); | |
b.accumulator().accept(acc._2, t); | |
}, | |
(a1, a2) -> T2.of( | |
a.combiner().apply(a1._1, a2._1), | |
b.combiner().apply(a1._2, a2._2) | |
), | |
(acc) -> f.apply( | |
a.finisher().apply(acc._1), | |
b.finisher().apply(acc._2) | |
), | |
Stream.concat( | |
cs1.contains(CONCURRENT) && cs2.contains(CONCURRENT) ? Stream.of(CONCURRENT) : Stream.empty(), | |
cs1.contains(UNORDERED) && cs2.contains(UNORDERED) ? Stream.of(UNORDERED) : Stream.empty() | |
).toArray(Characteristics[]::new) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment