Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the better alternative to following if-else ladder in java?

Situation : I am examining filenames , the filename is stored in a String variable called str and according to the conditions checked in if statements i am setting the value of a variable called mailType .

if(str.contains("template"))
        {                   
          if(str.contains("unsupported"))
              mailType="unsupported";      
              else
                  if(str.contains("final_result"))                
                      mailType="final_result";            
                  else
                      if(str.contains("process_success"))
                          mailType="Process Success"; 
                      else
                          if(str.contains("receive"))                         
                              mailType="Receive";                         
                          else
                          if(str.contains("sen"))
                              mailType="sent"; 
                          else
                              if(str.contains("welcome"))
                                  mailType="welcome";
                              else
                                  if(str.contains("manual"))
                                     mailType="Manual";                    
        }       
        else                
if(str.contains("properties"))
        {

          if(str.contains("unsupported"))
              mailType="unsupported";      
              else
                  if(str.contains("final_result"))                
                      mailType="final_result";            
                  else
                      if(str.contains("process_success"))
                          mailType="Process Success"; 
                      else
                          if(str.contains("receive"))                         
                              mailType="Receive";                         
                          else
                          if(str.contains("sen"))
                              mailType="sent"; 
                          else
                              if(str.contains("welcome"))
                                  mailType="welcome";
                              else
                                  if(str.contains("manual"))
                                     mailType="Manual";

        }

Problem : Is there any better way to do this in java that shortens my code and is memory friendly ?

like image 892
varun singhal Avatar asked Apr 15 '16 09:04

varun singhal


People also ask

Which is correct for if-else ladder?

The conditional expressions are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed, and the rest of the ladder is bypassed. If non of the conditions is true, then the final else statement will be executed.

What are the drawbacks of if-else ladder?

Disadvantages: if-else statements increase the number of code paths to be tested. If there are a lot of if statements the code sometimes becomes unreadable and complex, in such cases we use Switch case statement.

What is the difference between nested IF and ELSE IF ladder in Java?

Nested if()...else statements take more execution time (they are slower) in comparison to an if()...else ladder because the nested if()...else statements check all the inner conditional statements once the outer conditional if() statement is satisfied, whereas the if()..else ladder will stop condition testing once any ...

Is else if ladder and if-else ladder are same?

In programming, if-else-if statement is also known as if-else-if ladder. It is used when there are more than two possible action based on different conditions.


1 Answers

Use a LinkedHashMap<String, String>:

LinkedHashMap<String, String> mapping = new LinkedHashMap<>();
mapping.put("unsupported", "unsupported");
mapping.put("final_result", "final_result");
// ... etc

Then iterate the map until you find a matching key:

for (Map.Entry<String, String> entry : mapping.entrySet()) {
  if (str.contains(entry.getKey()) {
    mailType = entry.getValue();
    break;
  }
}

The key point here is that LinkedHashMap preserves insertion order (unlike HashMap) so you can actually specify the order in which you want to test for matches (other map implementations do this too, e.g. Guava's ImmutableMap; LinkedHashMap is simply one that you have out of the box).

If you need to nest this for the outer cases, you can simply apply the same pattern:

LinkedHashMap<String, LinkedHashMap<String, String>> outerMapping =
    new LinkedHashMap<>();
outerMapping.put("template", mapping);
outerMapping.put("properties", someOtherMapping);

And then just iterate through the keys in the same way:

for (Map.Entry<String, LinkedHashMap<String, String>> outerEntry : outerMapping.entrySet()) {
  if (str.contains(outerEntry.getKey()) {
    // Apply the iteration above, using outerEntry.getValue().
  }
}
like image 118
Andy Turner Avatar answered Oct 13 '22 11:10

Andy Turner