How to store enum to map using Java 8 stream API

别来无恙 提交于 2019-12-10 04:10:02

问题


I have an enum with another enum as a parameter

public enum MyEntity{
   Entity1(EntityType.type1,
    ....


   MyEntity(EntityType type){
     this.entityType = entityType;
   }
}

I want to create a method that return the enum by type

public MyEntity getEntityTypeInfo(EntityType entityType) {
        return lookup.get(entityType);
    }

usually I would have written

private static final Map<EntityType, EntityTypeInfo> lookup = new HashMap<>();

static {
    for (MyEntity d : MyEntity.values()){
        lookup.put(d.getEntityType(), d);
    }
}

What is the best practice to write it with java stream?


回答1:


I guess there are some typos in your code (the method should be static in my opinion, your constructor is doing a no-op at the moment), but if I'm following you, you can create a stream from the array of enums and use the toMap collector, mapping each enum with its EntityType for the keys, and mapping the instance itself as a value:

private static final Map<EntityType, EntityTypeInfo> lookup =
    Arrays.stream(EntityTypeInfo.values())
          .collect(Collectors.toMap(EntityTypeInfo::getEntityType, e -> e));

The toMap collector does not make any guarantee about the map implementation returned (although it's currently a HashMap), but you can always use the overloaded variant if you need more control, providing a throwing merger as parameter.

You could also use another trick with a static class, and fill the map in the constructor.



来源:https://stackoverflow.com/questions/31112967/how-to-store-enum-to-map-using-java-8-stream-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!