Optimizing Java if‑else Statements: Enums, Ternary Operators, Streams, Maps, and Optional
This article presents several techniques for refactoring verbose Java if‑else code—including strategy enums, ternary operators, Stream API predicates, Map and Enum look‑ups, and the Optional class—to produce cleaner, more maintainable backend implementations.
The author explains why excessive use of if‑else statements feels procedural and redundant, and shares practical ways to refactor them in Java.
1. Strategy enum – Instead of creating many strategy classes, combine the strategy pattern with an enum to centralize the logic and reduce class proliferation.
2. Ternary operator – Replace simple conditional assignments and method calls with a single line using the ternary operator.
String id="";
if(flag){
id="a";
}else{
id="b";
}
// becomes
id = flag ? "a" : "b";Similarly, conditional collection updates can be simplified:
Set
set1 = new HashSet<>();
Set
set2 = new HashSet<>();
if(flag){
set1.add(id);
}else{
set2.add(id);
}
// becomes
(flag ? set1 : set2).add(id);3. Stream API – Use anyMatch , allMatch , and noneMatch to collapse multiple logical checks into a single expressive statement.
List
list = Arrays.asList("a","b","c","d","");
boolean anyMatch = list.stream().anyMatch(s -> StringUtils.isEmpty(s));
boolean allMatch = list.stream().allMatch(s -> StringUtils.isEmpty(s));
boolean noneMatch = list.stream().noneMatch(s -> StringUtils.isEmpty(s));For a series of OR conditions:
if (Stream.of(str1, str2, str3, str4, str5, str6).anyMatch(s -> StringUtils.isEmpty(s))) {
// ...
}For AND conditions, replace with allMatch similarly.
4. Map lookup – When many branches return constant values, store the mapping in an immutable Map and retrieve the result directly.
public static final Map
dayMap = ImmutableMap.
builder()
.put("Monday", "今天上英语课")
.put("Tuesday", "今天上语文课")
.put("Wednesday", "今天上数学课")
.put("Thursday", "今天上音乐课")
.put("Sunday", "今天上编程课")
.build();
public String getDay(String day) {
return dayMap.get(day);
}5. Enum lookup – An enum with associated values can serve the same purpose as the map, providing type safety.
public enum DayEnum {
Monday("今天上英语课"),
Tuesday("今天上语文课"),
Wednesday("今天上数学课"),
Thursday("今天上音乐课"),
Sunday("今天上编程课");
public final String value;
DayEnum(String value) { this.value = value; }
}
public String getDay(String day) {
return DayEnum.valueOf(day).value;
}6. Optional for null‑safe navigation – Replace deeply nested null checks with the Optional API to avoid NullPointerException .
String name = Optional.ofNullable(school)
.flatMap(School::getGrades)
.flatMap(Grades::getStuendt)
.map(Student::getName)
.orElse(null);These techniques collectively make Java code more concise, readable, and less error‑prone.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.