gpt4 book ai didi

java - 如何使用 Java 8 简化链式 if 条件

转载 作者:行者123 更新时间:2023-11-29 07:33:21 24 4
gpt4 key购买 nike

   public class ShiftPatternDTO{
private boolean monday;
private boolean tuesday;
private boolean wednesday;
private boolean thursday;
private boolean friday;
private boolean saturday;
private boolean sunday;

public boolean isMonday() {
return monday;
}


public boolean isTuesday() {
return tuesday;
}


public boolean isWednesday() {
return wednesday;
}


public boolean isThursday() {
return thursday;
}



public boolean isFriday() {
return friday;
}


public boolean isSaturday() {
return saturday;
}


public boolean isSunday() {
return sunday;
}
}

public enum WeekDay {

MONDAY("Monday", 1),
TUESDAY("Tuesday", 2),
WEDNESDAY("Wednesday", 3),
THURSDAY("Thursday", 4),
FRIDAY("Friday", 5),
SATURDAY("Saturday", 6),
SUNDAY("Sunday", 7);
}

private Set<WeekDay> getWeekPattern(ShiftPatternDTO shiftPattern) {
Set<WeekDay> weekPatterns = new LinkedHashSet<>();
if (shiftPattern.isMonday()) {
weekPatterns.add(WeekDay.MONDAY);
}
if (shiftPattern.isTuesday()) {
weekPatterns.add(WeekDay.TUESDAY);
}
if (shiftPattern.isWednesday()) {
weekPatterns.add(WeekDay.WEDNESDAY);
}
if (shiftPattern.isThursday()) {
weekPatterns.add(WeekDay.THURSDAY);
}
if (shiftPattern.isFriday()) {
weekPatterns.add(WeekDay.FRIDAY);
}
if (shiftPattern.isSaturday()) {
weekPatterns.add(WeekDay.SATURDAY);
}
if (shiftPattern.isSunday()) {
weekPatterns.add(WeekDay.SUNDAY);
}
return weekPatterns;
}

上面的代码是使用 Java 7 编写的。我正在尝试将其重构为 Java 8。我花了一些时间使用 Optional 实用程序,但无法得出解决方案这个问题,请有人帮忙吗?我不想看到我的代码中的一系列 If 条件,这正是我要删除的内容。

我已经给出了我的代码的基本骨架结构。请注意,该问题是针对 Java 8 的,因此可以接受简单的回答“不,您需要遵循本论坛中建议的其他选项”

最佳答案

如果 ShiftPatternDTO 应保持不变,则使用枚举来保存谓词:

public enum WeekDay {
MONDAY("Monday", 1, ShiftPatternDTO::isMonday),
TUESDAY("Tuesday", 2, ShiftPatternDTO::isTuesday),
WEDNESDAY("Wednesday", 3, ShiftPatternDTO::isWednesday),
THURSDAY("Thursday", 4, ShiftPatternDTO::isThursday),
FRIDAY("Friday", 5, ShiftPatternDTO::isFriday),
SATURDAY("Saturday", 6, ShiftPatternDTO::isSaturday),
SUNDAY("Sunday", 7, ShiftPatternDTO::isSunday);

public final String name;
public final int num;
public final Predicate<ShiftPatternDTO> pred;

private WeekDay(String name, int num, Predicate<ShiftPatternDTO> pred) {
this.name = name;
this.num = num;
this.pred = pred;
}
}

private Set<WeekDay> getWeekPatternNew(ShiftPatternDTO shiftPattern) {
return
Arrays.stream(WeekDay.values())
.filter(wd -> wd.pred.test(shiftPattern))
.collect(Collectors.toSet());
}

关于java - 如何使用 Java 8 简化链式 if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39270694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com