使用位运算存储多选值

young 641 2022-10-23
public enum WeekEnum {
    MONDAY(1, "周一"),
    TUESDAY(1<<1, "周二"),
    Wednesday(1<<2, "周三"),
    Thursday(1<<3, "周四"),
    Friday(1<<4, "周五"),
    Saturday(1<<5, "周六"),
    Sunday(1<<6, "周天"),

    ;


    private Integer value;
    private String name;

    WeekEnum(Integer value, String name) {
        this.value = value;
        this.name = name;
    }

    public Integer getValue() {
        return value;
    }

    public String getName() {
        return name;
    }

    static Integer getValueByWeek(List<WeekEnum> weeks) {
        return weeks.stream().mapToInt(e -> e.getValue()).reduce((k1, k2) -> k1 | k2).getAsInt();
    }

    static List<WeekEnum> getWeekByValue(Integer value) {
        return Arrays.stream(WeekEnum.values()).filter(e -> (value & e.getValue()) == e.getValue()).collect(Collectors.toList());
    }
}