Java 枚举类转换List

1. 定义两个枚举类
⏹学生教育状态枚举类

public enum EducateStatusEnum {

    // 学生的学业状态
    IN_STUDYING((short) 1, "在读"),
    UNDERGRADUATE((short) 2, "肆业"),
    SUSPENDED((short) 3, "休学"),
    DROPPED((short) 4, "辍学"),
    QUITED((short) 5, "退学"),
    GRADUATED((short) 6, "已毕业");

    public short code;
    public String name;
 
    EducateStatusEnum(Short code, String name) {
        this.code = code;
        this.name = name;
    }
 
    public int getCode() {
        return this.code;
    }
 
    public String getName() {
        return this.name;
    }
 
    public static EducateStatusEnum findEnumByCode(Integer code) {
 
        for (EducateStatusEnum statusEnum : EducateStatusEnum.values()) {
            if (statusEnum.getCode() == code) {
                return statusEnum;
            }
 
        }
        throw new IllegalArgumentException("code is not support");
 
    }
 
    public static EducateStatusEnum findEnumByName(String name) {
        for (EducateStatusEnum statusEnum : EducateStatusEnum.values()) {
            if (statusEnum.getName().equals(name)) {
                return statusEnum;
            }
 
        }
        throw new IllegalArgumentException("name is not support");
    }
}

⏹性别枚举类

public enum SexEnum {("1"),("2");

    public String code;

    SexEnum(String code) {
        this.code = code;
    }

    public String getCode() {
        return this.code;
    }

    public static SexEnum findSexEnumByCode(String code) {

        for (SexEnum sexEnum : SexEnum.values()) {
            if (code.equals(sexEnum.getCode())) {
                return sexEnum;
            }
        }
        return null;
    }

    public static SexEnum findSexEnumByName(String name) {

        for (SexEnum sexEnum : SexEnum.values()) {
            if (name.equals(sexEnum.name())) {
                return sexEnum;
            }
        }
        return null;
    }
}

2. 转换工具类

import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

public class EnumListUtil {

    private static final String ENUM_CLASSPATH = "java.lang.Enum";

    private static List<Field> commonHandle(Class<?> enumClass) {

        // 获取所有public方法
        Method[] methods = enumClass.getMethods();
        List<Field> fieldList = new ArrayList<>();

        // 1.通过get方法提取字段,避免get作为自定义方法的开头,建议使用'find'或其余命名
        Arrays.stream(methods).map(Method::getName)
                .filter(methodName -> methodName.startsWith("get")
                        && !"getDeclaringClass".equals(methodName)
                        && !"getClass".equals(methodName))
                .forEachOrdered(methodName -> {
                    try {
                        Field field = enumClass.getDeclaredField(StringUtils.uncapitalize(methodName.substring(3)));
                        if (!ObjectUtils.isEmpty(field)) {
                            fieldList.add(field);
                        }
                    } catch (NoSuchFieldException | SecurityException e) {
                        e.printStackTrace();
                    }
                });

        return fieldList;
    }
	
	// 枚举类转换List,元素为自定义实体类
    public static List<Select2Item> enumToSelect2List(Class<?> enumClass) {

        List<Select2Item> resultList = new ArrayList<>();
        if (!ENUM_CLASSPATH.equals(enumClass.getSuperclass().getCanonicalName())) {
            return resultList;
        }

        List<Field> fieldList = commonHandle(enumClass);

        // 2.将字段作为key,逐一把枚举值作为value存入list
        if (CollectionUtils.isEmpty(fieldList)) {
            return resultList;
        }

        Enum<?>[] enums = (Enum[]) enumClass.getEnumConstants();
        Select2Item select2Item = null;
        for (Enum<?> anEnum : enums) {

            select2Item = new Select2Item();
            for (Field field : fieldList) {

                field.setAccessible(true);
                try {
                    select2Item.setId(field.get(anEnum).toString());
                    select2Item.setText(anEnum.name());
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 将Select2Item添加到集合中
            resultList.add(select2Item);
        }
        return resultList;
    }
	
	// 枚举类转换List,元素为Map
    public static List<Map<String, Object>> enumToMapList(Class<?> enumClass) {

        List<Map<String, Object>> resultList = new ArrayList<>();
        if (!ENUM_CLASSPATH.equals(enumClass.getSuperclass().getCanonicalName())) {
            return resultList;
        }

        List<Field> fieldList = commonHandle(enumClass);

        // 2.将字段作为key,逐一把枚举值作为value存入list
        if (CollectionUtils.isEmpty(fieldList)) {
            return resultList;
        }

        Enum<?>[] enums = (Enum[]) enumClass.getEnumConstants();
        Map<String, Object> map = null;
        for (Enum<?> anEnum : enums) {

            map = new HashMap<>(fieldList.size());
            for (Field field : fieldList) {

                field.setAccessible(true);
                try {
                    // 向map集合添加字段名称和字段值
                    map.put(field.getName(), field.get(anEnum));
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            // 将Map添加到集合中
            resultList.add(map);
        }
        return resultList;
    }
}

3. 调用转换
Java 枚举类转换List_第1张图片


结合Java8的Stream流来将枚举类进行遍历封装处理

⏹枚举类

public enum MasterEnumType {

    基础数据1("1"),
    基础数据2("2"),
    基础数据3("3"),
    基础数据4("4"),
    基础数据5("5"),
    基础数据6("6"),
    基础数据7("7");

    private String code;

    MasterEnumType(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}
  • 获取枚举类中的code列表
List<String> codeList = Stream.of(MasterEnumType.values())
							  .map(MasterEnumType::getCode)
							  .collect(Collectors.toList());
System.out.println(codeList);  // [1, 2, 3, 4, 5, 6, 7]
  • 枚举类封装为Map

因为使用了LinkedHashMap,因此是有序的.

Map<String, String> map = new LinkedHashMap<>();
Arrays.asList(MasterEnumType.values())
      .forEach((item -> map.put(item.name(), item.getCode())));
System.out.println(map);  // {基础数据1=1, 基础数据2=2, 基础数据3=3, 基础数据4=4, 基础数据5=5, 基础数据6=6, 基础数据7=7}
  • 封装为实体类List
List<Select2Item> select2Items = new ArrayList<>();
Arrays.asList(MasterEnumType.values())
      .forEach(item -> select2Items.add(new Select2Item(item.getCode(), item.name())));
System.out.println(select2Items);  
// [Select2Item{id='1', text='基础数据1'}, Select2Item{id='2', text='基础数据2'}, Select2Item{id='3', text='基础数据3'}, Select2Item{id='4', text='基础数据4'}, Select2Item{id='5', text='基础数据5'}, Select2Item{id='6', text='基础数据6'}, Select2Item{id='7', text='基础数据7'}]

你可能感兴趣的:(Java,枚举)