Java 将枚举存入List集合

基本思路就是新建一个字段跟枚举一致的类A,然后写个方法,获取枚举的值循环存入到list<A>中,示例如下:

枚举类:

// 套餐枚举
public enum BalanceType {
balance_type0(0, "套餐1"), balance_type1(1, "套餐2"), balance_type2(
2, "套餐3"), balance_type3(3, "套餐4"), balance_type4(4,
"套餐5"), balance_type5(5, "套餐6"), balance_type6(6, "套餐7"), balance_type7(
7, "套餐8"), balance_type8(8, "套餐9"), balance_type9(9, "套餐10"), balance_type10(
10, "套餐11");
private Integer code;
private String desc;
private BalanceType(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}

首先,根据枚举类创建一个dto出来,如下:(字段根据自己需要定义)

public class EnumOrderTypeVo implements Serializable{

private static final long serialVersionUID = 1L;

private Integer code; //类型编号
private String desc;  //类型描述
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}


接下来,我们可以通过java方法来实现将枚举的值存入dto的list中了,方法如下:

public List<EnumOrderTypeVo> getOrderType(String requestId){
ResultInfoVo rinf = new ResultInfoVo(requestId);
ArrayList<EnumOrderTypeVo> list = new ArrayList<EnumOrderTypeVo>();
for(BalanceType type : BalanceType .values()){
EnumOrderTypeVo type = new EnumOrderTypeVo();
type.setCode(type.getCode());
type.setDesc(type.getDesc());
list.add(type);
}
System.out.println(list.size());
ListDataVo<ArrayList<EnumOrderTypeVo>> listData = new ListDataVo<ArrayList<EnumOrderTypeVo>>(list);
return list;
}


至此就完成了将枚举值存入到list以便封装传到前端显示了

猜你喜欢

转载自blog.csdn.net/qq_22158021/article/details/78091978