我有一个根据条件返回竞赛列表的方法。我可以有多个条件,并且我希望有使用 java 8 执行此方法的最佳方法。 这是我的方法:
public static final String COMPETITION_AGE_18_30 = "compet1";
public static final String COMPETITION_AGE_30_40 = "compet2";
public List<Competition> getCompetitionss(String competAge) {
if (COMPETITION_AGE_18_30.equals(competAge)) {
return List.of(
CompetitionNatation,
CompetitionFoot,
CompetitionHand,
CompetitionNatation);
} else if (COMPETITION_AGE_30_40.equals(competAge)) {
return List.of(
CompetitionRoller
);
} else {
return List.of();
}
}
我怎样才能用最好的方式重构这个方法
不确定如何填充这些列表,但将组合存储在映射中将使您的代码性能更高且更具可读性。比如:
public static List<Competition> getCompetitions(String competAge) {
Map<String,List<Competition>> map = Map.of(
COMPETITION_AGE_18_30, List.of(CompetitionNatation, CompetitionFoot, CompetitionHand, CompetitionNatation),
COMPETITION_AGE_30_40, List.of(CompetitionRoller));
return map.getOrDefault(competAge, List.of());
}
在 Java 14+ 中使用 switch statements 让你的意图更加清晰。
public List<Competition> getCompetitionss( final String competAge ) {
return
switch ( competAge )
case COMPETITION_AGE_18_30 -> List.of( … ) ;
case COMPETITION_AGE_30_40 -> List.of( CompetitionRoller ) ;
default -> List.of() ;
}
}
但是,如果有的话,执行起来会不知不觉地更快。
谨防过早优化。您的问题的代码极不可能影响您的应用程序的性能。