15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Collectors.toMapで任意のMapクラスを返す

Last updated at Posted at 2017-01-31

Collectors.toMapは通常、Mapクラスのインスタンスを返却します。

Collectors.toMapの例
enum ENUM {
	ENUM_1
	,ENUM_2
	,ENUM_3
	,ENUM_4
	,ENUM_5
	,ENUM_6
}


Map<ENUM, Integer> map = Stream.of(ENUM.values())
		.collect(Collectors.toMap(
			e -> e
			,e -> e.ordinal()
		));

HashMap、LinkedHashMap、TreeMapなど、Mapクラスの任意の子クラスを返したい場合は、引数4つの Collectors.toMap を使えば可能になります。

Collectors.toMap
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
Collectors.toMapでHashMapを返す例
HashMap<ENUM, Integer> map= Stream.of(ENUM.values())
		.collect(Collectors.toMap(
			e -> e
			,e -> e.ordinal()
			,(e1, e2) -> e1
			,HashMap::new
		));

Collectors.toMapでEnumMapを返したい場合ですが、EnumMapは引数なしコンストラクタを持ってません。この場合どう実装すれば良いかというと、コンストラクタ参照は無理なのでラムダ式で実装すればOKです。

Collectors.toMapでEnumMapを返す例1
EnumMap<ENUM, Integer> map = Stream.of(ENUM.values())
		.collect(Collectors.toMap(
			e -> e
			,e -> e.ordinal()
			,(e1, e2) -> e1
			,() -> {
				EnumMap<ENUM, Integer> ret = new EnumMap<>(ENUM.class);
				return ret;
			}
		));

いろいろ省略すると以下の様に書くことも出来ます。

Collectors.toMapでEnumMapを返す例2
EnumMap<ENUM, Integer> map = Stream.of(ENUM.values())
		.collect(Collectors.toMap(
			e -> e
			,e -> e.ordinal()
			,(e1, e2) -> e1
			,() -> new EnumMap<>(ENUM.class)
		));
15
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?