英文:
Java Initialize EnumBiMap From Two Enum Types
问题
什么是初始化EnumBiMap的最便捷方式,使其从两种不同的枚举类型中进行初始化?我有以下情景:
public enum First {
A,
B,
C
}
和
public enum Second {
ALPHA,
BETA,
GAMMA
}
我尝试过类似以下的方式
private static EnumBiMap<First, Second> typeMap =
EnumBiMap<First, Second>.create(
Arrays.stream(First.values()).collect(Collectors.toMap(
Function.identity(), type -> {
switch(type) {
case First.A:
return Second.ALPHA;
case First.B:
return Second.BETA;
default:
return Second.GAMMA;
}})));
但是我失去了类型信息,所以出现了错误。有没有更好的方法来获得这个映射?我也不能够通过连续使用put()来实现,因为put()只会返回值,而不是返回对映射的引用。在我的情况下,这个映射也可以是不可变的。
英文:
What's the most convenient way to initialize an EnumBiMap from two different enum types? I have the following scenario:
public enum First {
A,
B,
C
}
and
public enum Second {
ALPHA,
BETA,
GAMMA
}
I have tried something like
private static EnumBiMap<First, Second> typeMap =
EnumBiMap<First, Second>.create(
Arrays.stream(First.values()).collect(Collectors.toMap(
Function.identity(), type -> {
switch(type) {
case First.A:
return Second.ALPHA;
case First.B:
return Second.BETA;
default:
return Second.GAMMA
}})));
But I lose the type information so I get errors. Is there a nicer way to get this mapping? I also can't daisy-chain puts since put() just returns the value as opposed to a reference to the map. In my case, the map could also be immutable.
答案1
得分: 1
import com.google.common.collect.EnumBiMap;
import com.google.common.collect.Streams;
import static java.util.Arrays.stream;
EnumBiMap<First, Second> map = EnumBiMap.create(First.class, Second.class);
Streams.forEachPair(stream(First.values()), stream(Second.values()), map::put);
英文:
import com.google.common.collect.EnumBiMap;
import com.google.common.collect.Streams;
import static java.util.Arrays.stream;
EnumBiMap<First, Second> map = EnumBiMap.create(First.class, Second.class);
Streams.forEachPair(stream(First.values()), stream(Second.values()), map::put);
答案2
得分: 0
你所采用的映射方式似乎是一种按顺序进行映射。然后,你可以使用枚举的 .ordinal()
方法来获取枚举的序号值,以创建映射。
EnumBiMap<First, Second>.create(
Arrays.stream(First.values())
.collect(Collectors.toMap(Function.identity(),
e -> Second.values()[e.ordinal()])));
英文:
The way you are mapping seems like mapping ordinally. Then you can use the ordinal value using .ordinal()
of the enum to create the map.
EnumBiMap<First, Second>.create(
Arrays.stream(First.values())
.collect(Collectors.toMap(Function.identity(),
e -> Second.values()[e.ordinal()])));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论