Skip to content

Commit

Permalink
require non-null default key
Browse files Browse the repository at this point in the history
  • Loading branch information
xzel23 committed Nov 7, 2024
1 parent 5e742a8 commit 5e4ed8e
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions utility/src/main/java/com/dua3/utility/lang/BatchCollector.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,14 @@
*/
public class BatchCollector<T extends @Nullable Object, K> implements Collector<T, Deque<Pair<K, List<T>>>, List<Pair<K, List<T>>>> {
private final Function<? super T, ? extends K> keyMapper;
private final @Nullable K defaultKey;

/**
* Constructor.
*
* @param keyMapper mapping that maps each item to the grouping key
*/
public BatchCollector(Function<? super T, ? extends K> keyMapper) {
this(keyMapper, null);
this.keyMapper = keyMapper;
}

/**
Expand All @@ -45,9 +44,8 @@ public BatchCollector(Function<? super T, ? extends K> keyMapper) {
* @param keyMapper the key mapper
* @param defaultKey the default key
*/
public BatchCollector(Function<? super T, ? extends K> keyMapper, @Nullable K defaultKey) {
this.keyMapper = keyMapper;
this.defaultKey = defaultKey;
public BatchCollector(Function<? super T, ? extends @Nullable K> keyMapper, K defaultKey) {
this(t -> Objects.requireNonNullElse(keyMapper.apply(t), defaultKey));
}

@Override
Expand All @@ -63,7 +61,7 @@ public BiConsumer<Deque<Pair<K, List<T>>>, T> accumulator() {
List<T> bucket;
if (accu.isEmpty() || (!Objects.equals(key, accu.peekLast().first()))) {
bucket = new ArrayList<>();
accu.addLast(Pair.of(key == null ? defaultKey : key, bucket));
accu.addLast(Pair.of(key, bucket));
} else {
bucket = accu.peekLast().second();
}
Expand Down

0 comments on commit 5e4ed8e

Please sign in to comment.