You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将枚举值与标签流式转换为List<ProductActionItem>对象

如何将枚举的枚举值与标签流式转换为List对象?

现有如下定义的ProductActions枚举类:

public enum ProductActions {
    BUY("Buy"),
    SELL("Sell"),
    Transfer("Transfer"),

    public final String label;

    ProductActions(String label) {
        this.label = label;
    }
}

希望将其转换为List<ProductActionItem>集合,对应的实体类定义如下:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ProductActionItem {
    private String productAction;
    private String productLabel;
}

目前编写的代码仅能收集枚举的label属性:

return Arrays.stream(ProductActions.values())
             .map(e -> e.label).collect(Collectors.toList());

正确实现方式

你需要在map操作中将每个枚举实例转换为ProductActionItem对象,以下是两种常用实现:

1. 使用全参构造器

借助实体类@AllArgsConstructor生成的构造器,直接传入枚举名称(通过name()方法获取)和标签:

return Arrays.stream(ProductActions.values())
             .map(e -> new ProductActionItem(e.name(), e.label))
             .collect(Collectors.toList());

2. 使用Builder模式

利用实体类的@Builder注解,通过链式调用构建对象:

return Arrays.stream(ProductActions.values())
             .map(e -> ProductActionItem.builder()
                                        .productAction(e.name())
                                        .productLabel(e.label)
                                        .build())
             .collect(Collectors.toList());

两种方式都能完整将枚举的枚举值(名称)和标签映射到ProductActionItem的对应字段,最终得到目标List集合。

内容的提问来源于stack exchange,提问作者mattsmith5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:35:27