1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public class XCollectors {
public static <K, V, E extends Map.Entry<K, ? extends Collection<V>>> Collector<E,Map<V,K>,Map<V,K>> reverseOfMapOfListCollector() {
return reverseOfMapOfListCollector(HashMap::new);
}
public static <K, V, E extends Map.Entry<K, ? extends Collection<V>>> Collector<E,Map<V,K>,Map<V,K>> reverseOfMapOfListCollector(Supplier<Map<V, K>> supplier) {
return new Collector<E,Map<V,K>,Map<V,K>>() {
@Override
public Supplier<Map<V, K>> supplier() {
return supplier;
}
@Override
public Function<Map<V, K>, Map<V, K>> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return EnumSet.of(Characteristics.UNORDERED);
}
@Override
public BiConsumer<Map<V, K>, E> accumulator() {
return (m2, e)-> {
e.getValue()
.stream()
.peek(k-> {
if (m2.containsKey(k)) {
throw new IllegalStateException("Duplicate value "+k+" mapped to "+m2.get(k)+" and "+e.getKey());
}
})
.forEach(v-> m2.put(v, e.getKey()));
};
}
@Override
public BinaryOperator<Map<V, K>> combiner() {
return (m1, m2)-> {
m2.putAll(m1);
return m2;
};
}
};
}
} |
Partager