less than 1 minute read

2021-08-24-enum-map.md


import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@AllArgsConstructor
public enum Region {
    WW("WorldWide"),
    EU("EUR"),
    US("USA"),
    CH("CHN");
    private String region;

    public Map<String,String> toMap(){
        return Arrays.stream(this.getDeclaringClass().getDeclaredFields())
                .filter(field -> !field.isSynthetic() && !field.isEnumConstant())
                .collect(
                        Collectors.toMap(
                                field -> field.getName(),
                                field -> getFieldValue(field))
                );
    }

    private String getFieldValue(Field field) {
        try {
            return (String) field.get(this);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Comments