Member-only story

How to replace multiple if else condition with map in Java?

Gain Java Knowledge
2 min readSep 22, 2024

--

In this title, we will learn how to replace multiple if else condition with Map in java to make our code more clean.

As we know in some cases, we need to add multiple if else conditions. Below is the example code inside getJuice(String fruit) :

package com.example.spring_boot_rule_engine_demo;

public class Remove_If_Else {

public static void main(String[] args) {
Remove_If_Else obj = new Remove_If_Else();
System.out.println(obj.getJuice("Coconut"));

}

public String getJuice(String fruit){
if("Orange".equalsIgnoreCase(fruit)) {
return processOrangeJuice();
} else if("Apple".equalsIgnoreCase(fruit)) {
return processAppleJuice();
}else if("Coconut".equalsIgnoreCase(fruit)){
return processCoconutJuice();
}else{
// do nothing
return "no juice";
}
}

private String processCoconutJuice() {
return "Coconut juice is ready.";
}

private String processAppleJuice() {
return "Apple juice is ready.";
}

private String processOrangeJuice() {
return "Orange juice is ready.";
}


}

So How can we replace these multiple if-else conditions with Map?

  • For the String literals, we can use the HashMap

--

--

Gain Java Knowledge
Gain Java Knowledge

Written by Gain Java Knowledge

The Java programming language is one of the most popular languages today. Stay up to date with news, certifications, free learning resources and much more.

Responses (2)