Created
February 27, 2017 07:35
-
-
Save Satomaru/77a2b1a5316923b993aa325a8a66a17d to your computer and use it in GitHub Desktop.
列挙型セットマップを作成します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 列挙型セットマップを作成します。 | |
*/ | |
public final class EnumSetMapBuilder { | |
/** コレクター特性。 */ | |
public static final Set<Collector.Characteristics> ENUM_SET_MAP_COLLECTOR_CHARS = | |
Collections.singleton(Collector.Characteristics.UNORDERED); | |
/** | |
* 列挙型セットマップを作成する為のコレクターを作成します。 | |
* | |
* @param keyType キーとなる列挙型 | |
* @param keyGenerator 値となる列挙型から、キーとなる列挙型を作成する関数 | |
* @return 列挙型セットマップを作成する為のコレクター | |
*/ | |
public static <K extends Enum<K>, V extends Enum<V>> Collector<V, ?, Map<K, Set<V>>> collector( | |
Class<K> keyType, | |
Function<V, K> keyGenerator) { | |
return new Collector<V, EnumMap<K, EnumSet<V>>, Map<K, Set<V>>>() { | |
@Override | |
public Supplier<EnumMap<K, EnumSet<V>>> supplier() { | |
return () -> new EnumMap<>(keyType); | |
} | |
@Override | |
public BiConsumer<EnumMap<K, EnumSet<V>>, V> accumulator() { | |
return (map, value) -> { | |
K key = keyGenerator.apply(value); | |
EnumSet<V> set = map.get(key); | |
if (set != null) { | |
set.add(value); | |
} else { | |
map.put(key, EnumSet.of(value)); | |
} | |
}; | |
} | |
@Override | |
public BinaryOperator<EnumMap<K, EnumSet<V>>> combiner() { | |
return (map1, map2) -> { | |
map2.forEach((key, set) -> map1.merge(key, set, (set1, set2) -> { | |
set1.addAll(set2); | |
return set1; | |
})); | |
return map1; | |
}; | |
} | |
@Override | |
public Function<EnumMap<K, EnumSet<V>>, Map<K, Set<V>>> finisher() { | |
return map -> map.entrySet().stream().collect( | |
Collectors.collectingAndThen( | |
Collectors.toMap( | |
Map.Entry::getKey, | |
e -> Collections.unmodifiableSet(e.getValue()), | |
(set1, set2) -> set1, | |
() -> new EnumMap<>(keyType) | |
), | |
Collections::unmodifiableMap | |
) | |
); | |
} | |
@Override | |
public Set<Collector.Characteristics> characteristics() { | |
return ENUM_SET_MAP_COLLECTOR_CHARS; | |
} | |
}; | |
} | |
private EnumSetMapBuilder() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment