How to store enum to map using Java 8 stream API

前端 未结 2 962
梦谈多话
梦谈多话 2021-02-20 12:47

I have an enum with another enum as a parameter

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


   MyEntity(EntityType ty         


        
相关标签:
2条回答
  • 2021-02-20 12:57
    public enum FibreSpeed {
            a30M( "30Mb Fibre Connection - Broadband Only", 100 ),
            a150M( "150Mb Fibre Connection - Broadband Only", 300 ),
            a1G( "1Gb Fibre Connection - Broadband Only", 500 ),
            b30M( "30Mb Fibre Connection - Broadband & Phone", 700 ),
            b150M( "150Mb Fibre Connection - Broadband & Phone", 900 ),
            b1G( "1Gb Fibre Connection - Broadband & Phone", 1000 );
    
            public String speed;
            public int    weight;
    
            FibreSpeed(String speed, int weight) {
                this.speed = speed;
                this.weight = weight;
            }
    
            public static Map<String, Integer> SPEEDS = Stream.of( values() ).collect( Collectors.toMap( k -> k.speed, v -> v.weight ) );
        }
    
    0 讨论(0)
  • 2021-02-20 13:10

    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.

    0 讨论(0)
提交回复
热议问题