[JAVA] Returns any Map class in Collectors.toMap

Collectors.toMap usually returns an instance of the Map class.

Collectors.toMap example


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()
		));

If you want to return any child class of the Map class, such as HashMap, LinkedHashMap, TreeMap, you can use Collectors.toMap with four arguments.

Collectors.toMap


toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)

Collectors.Example of returning HashMap with toMap


HashMap<ENUM, Integer> map= Stream.of(ENUM.values())
		.collect(Collectors.toMap(
			e -> e
			,e -> e.ordinal()
			,(e1, e2) -> e1
			,HashMap::new
		));

If you want Collectors.toMap to return EnumMap, EnumMap doesn't have an argument-free constructor. In this case, how to implement it is OK if you implement it with a lambda expression because it is impossible to refer to the constructor.

Collectors.Example 1 that returns EnumMap with toMap


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;
			}
		));

If you omit various things, you can also write as follows.

Collectors.Example 2 returning EnumMap with toMap


EnumMap<ENUM, Integer> map = Stream.of(ENUM.values())
		.collect(Collectors.toMap(
			e -> e
			,e -> e.ordinal()
			,(e1, e2) -> e1
			,() -> new EnumMap<>(ENUM.class)
		));

Recommended Posts

Returns any Map class in Collectors.toMap
Class in Ruby
NullpointException in injecting class
Write class inheritance in Ruby