如何使用Java 8流API存储枚举 [英] How to store enum to map using Java 8 stream API

查看:172
本文介绍了如何使用Java 8流API存储枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举与另一个枚举作为参数

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

通常我会写

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

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

用java流写最好的做法是什么? >

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

推荐答案

我想有一些你的代码中的打字错误(该方法在我看来应该是静态的,你的构造函数目前正在做一个no-op),但是如果我跟着你,你可以从枚举数组中创建一个流,然后使用 toMap collector,将每个枚举与它的 EntityType 映射到键,并将实例本身映射为一个值:

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

toMap 收藏者的不保证关于返回的地图实现(尽管它目前是一个 HashMap ),但您可以随时使用 overloaded variant如果需要更多的控件,提供一个投掷合并作为参数。

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.

这篇关于如何使用Java 8流API存储枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆