classlib: collectors partitioning by (#716)

This commit is contained in:
Ivan Hetman 2023-06-21 16:35:37 +03:00 committed by GitHub
parent 81124a084b
commit 23a6393267
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 0 deletions

View File

@ -30,6 +30,7 @@ import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
@ -357,4 +358,24 @@ public final class TCollectors {
this.b = b;
}
}
public static <T, A, R> TCollector<T, ?, Map<Boolean, R>> partitioningBy(Predicate<? super T> predicate,
TCollector<? super T, A, R> downstream) {
BiConsumer<A, ? super T> acc = downstream.accumulator();
return teeing(TCollector.of(downstream.supplier(), (res, el) -> {
if (!predicate.test(el)) {
acc.accept(res, el);
}
}, downstream.combiner(), downstream.finisher()),
TCollector.of(downstream.supplier(), (res1, el1) -> {
if (predicate.test(el1)) {
acc.accept(res1, el1);
}
}, downstream.combiner(), downstream.finisher()),
(fls, tr) -> Map.of(false, fls, true, tr));
}
public static <T> TCollector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) {
return partitioningBy(predicate, toList());
}
}

View File

@ -25,6 +25,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@ -178,4 +179,12 @@ public class CollectorsTest {
.collect(Collectors.teeing(Collectors.summingInt(String::length),
Collectors.averagingInt(String::length), (sum, avg) -> sum / avg)));
}
@Test
public void partitioningBy() {
Map<Boolean, Set<Integer>> grouped = IntStream.range(0, 10).boxed()
.collect(Collectors.partitioningBy(i -> i % 2 == 0, Collectors.toSet()));
assertEquals(Set.of(1, 3, 5, 7, 9), grouped.get(false));
assertEquals(Set.of(0, 2, 4, 6, 8), grouped.get(true));
}
}