Home > other >  Java: Getting all names and Labels in an Enum as a List Object
Java: Getting all names and Labels in an Enum as a List Object

Time:12-09

How do I stream a Enum Value-Label into a List object? Two

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

    public final String label;

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

Want to transfer into this List<ProductActionItem>

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

}

Working on Code:

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

Trying to use this Resource:

https://stackoverflow.com/a/28828117/15435022

CodePudding user response:

You are on the right track you just need to convert the enums to your new class. Assuming appropriate getter in the enum and constructor:

Arrays.stream(ProductActions.values())
    .map(pav -> new ProductActionItem(pav.name(), pav.label())
    .toList();
  • Related