org.conqat.lib.commons.collections.CollectionMapCollectorBase Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of teamscale-lib-commons Show documentation
Show all versions of teamscale-lib-commons Show documentation
Provides common utility functions
package org.conqat.lib.commons.collections;
import java.util.EnumSet;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.conqat.lib.commons.assertion.CCSMAssert;
/**
* Base class for stream {@link Collector}s of {@link CollectionMap}s.
*
* @param
* the type of input elements to the reduction operation
* @param
* the key type
* @param
* the value type (i.e. the values stored in the collections)
* @param
* the resulting {@link CollectionMap} type.
*/
/* package */ abstract class CollectionMapCollectorBase>
implements Collector {
/** Mapper from stream objects to {@link CollectionMap} keys. */
private final Function keyMapper;
/** Mapper from stream objects to {@link CollectionMap} values. */
private final Function valueMapper;
protected CollectionMapCollectorBase(@NonNull Function keyMapper, @NonNull Function valueMapper) {
CCSMAssert.isNotNull(keyMapper, () -> String.format("Expected \"%s\" to be not null", "keyMapper"));
CCSMAssert.isNotNull(valueMapper, () -> String.format("Expected \"%s\" to be not null", "valueMapper"));
this.keyMapper = keyMapper;
this.valueMapper = valueMapper;
}
@Override
public BiConsumer accumulator() {
return (collection, element) -> collection.add(keyMapper.apply(element), valueMapper.apply(element));
}
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public BinaryOperator combiner() {
return (collection1, collection2) -> {
// raw type required, because addAll (needlessly) expects exactly the same
// collection type
collection1.addAll((CollectionMap) collection2);
return collection1;
};
}
@Override
public Function finisher() {
return Function.identity();
}
@Override
public Set characteristics() {
return EnumSet.of(Characteristics.IDENTITY_FINISH);
}
}