refactor(util): add multiple key support to ObjectAggregator
This commit is contained in:
parent
630c8ddee5
commit
7287d44645
@ -1,6 +1,7 @@
|
||||
package net.tomatentum.marinara.registry;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@ -57,7 +58,7 @@ public class InteractionRegistry {
|
||||
.toList();
|
||||
|
||||
SlashCommandDefinition[] defs = new ObjectAggregator<InteractionIdentifier, RootCommandIdentifier, SlashCommandDefinition>(
|
||||
i -> (RootCommandIdentifier)i.rootNode(),
|
||||
i -> Arrays.asList((RootCommandIdentifier)i.rootNode()),
|
||||
SlashCommandDefinition::addIdentifier,
|
||||
SlashCommandDefinition::new)
|
||||
.aggregate(slashIdentifiers)
|
||||
|
@ -5,25 +5,40 @@ import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ObjectAggregator<O, K, V> {
|
||||
private Function<O, K> keySupplier;
|
||||
private Function<O, Iterable<K>> keySupplier;
|
||||
private BiConsumer<V, O> valueConsumer;
|
||||
private Function<K, V> defaultGenerator;
|
||||
|
||||
public ObjectAggregator(Function<O, K> keySupplier, BiConsumer<V, O> valueConsumer, Function<K, V> defaultGenerator) {
|
||||
public ObjectAggregator(
|
||||
Function<O, Iterable<K>> keySupplier,
|
||||
BiConsumer<V, O> valueConsumer,
|
||||
Function<K, V> defaultGenerator) {
|
||||
this.keySupplier = keySupplier;
|
||||
this.valueConsumer = valueConsumer;
|
||||
this.defaultGenerator = defaultGenerator;
|
||||
}
|
||||
|
||||
public ObjectAggregator(
|
||||
Function<O, Iterable<K>> keySupplier,
|
||||
BiConsumer<V, O> valueConsumer,
|
||||
Supplier<V> defaultGenerator) {
|
||||
this.keySupplier = keySupplier;
|
||||
this.valueConsumer = valueConsumer;
|
||||
this.defaultGenerator = _ -> defaultGenerator.get();
|
||||
}
|
||||
|
||||
public Collection<V> aggregate(Iterable<O> iterator) {
|
||||
Map<K, V> map = new HashMap<>();
|
||||
for (O element : iterator) {
|
||||
K key = this.keySupplier.apply(element);
|
||||
V value = map.getOrDefault(key, this.defaultGenerator.apply(key));
|
||||
this.valueConsumer.accept(value, element);
|
||||
map.putIfAbsent(key, value);
|
||||
Iterable<K> keys = this.keySupplier.apply(element);
|
||||
for (K key : keys) {
|
||||
V value = map.getOrDefault(key, this.defaultGenerator.apply(key));
|
||||
this.valueConsumer.accept(value, element);
|
||||
map.putIfAbsent(key, value);
|
||||
}
|
||||
}
|
||||
return map.values();
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user