How to save an enumeration for mapping using the Java 8 stream API

I have enum with another enum as parameter

 public enum MyEntity{ Entity1(EntityType.type1, .... MyEntity(EntityType type){ this.entityType = entityType; } } 

I want to create a method that returns enum by type

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

I would usually write

 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 for writing using java stream?

+6
source share
1 answer

I assume that there are typos in your code (the method should be static, in my opinion, your constructor is doing no-op at the moment), but if I follow you, you can create a stream from an array of enumerations and use the toMap collector. matching each enum with its EntityType for keys and matching 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 makes no warranties regarding the returned implementation of the map (although this is currently a HashMap ), but you can always use the overloaded version if you need more control, providing merge dumping as a parameter.

You can also use one more trick with a static class and fill the map in the constructor.

+13
source

Source: https://habr.com/ru/post/989936/


All Articles