Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple way to code multiple if conditions?

Tags:

java

I have the below piece of code in Java. I need to execute all of the if statements.Is there a better approach to code this.In each of the statement, I would then make a database call.

if (!keyAccntId.equalsIgnoreCase("-1") && !(segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
    templateOrder.add("1");
}
if (!keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
    templateOrder.add("2");
}
if (!keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && (regionId.equalsIgnoreCase("-1"))) {
    templateOrder.add("3");
}
if (keyAccntId.equalsIgnoreCase("-1") && !(segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
    templateOrder.add("4");
}
if (keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && !(regionId.equalsIgnoreCase("-1"))) {
    templateOrder.add("5");
}
if (keyAccntId.equalsIgnoreCase("-1") && (segmentId.equalsIgnoreCase("-1")) && (regionId.equalsIgnoreCase("-1"))) {
    templateOrder.add("6");
}
like image 858
user3707778 Avatar asked Nov 28 '22 01:11

user3707778


2 Answers

You could create a bitmask and switch on it:

public static final int KEY = 1;
public static final int SEGMENT = 2;
public static final int REGION = 4;

int value = 0;

if (keyAccntId.equalsIgnoreCase("-1")) {
    value += KEY;
}
if (segmentId.equalsIgnoreCase("-1")) {
    value += SEGMENT;
}
if (regionId.equalsIgnoreCase("-1")) {
    value += REGION;
}

That gives you 8 possible values, which you can switch on:

switch(value) {
case 0:
    // All false
    break;
case KEY:
    // only keyAccntId is true
    break;
case REGION:
    // only segmentId is true
    break;
case KEY + REGION:
    // segmentId and keyAccntId are true
    break;
// So on
}

edit

Added constants to improve readability

like image 82
njzk2 Avatar answered Dec 06 '22 08:12

njzk2


A shorter version of @njzk2's answer using Java 7.

public static final int KEY = 0b001, SEGMENT = 0b010, REGION = 0b100;

int comb = (keyAccntId.equals("-1") ? KEY : 0) +
        (segmentId.equals("-1") ? SEGMENT : 0) +
        (regionId.equals("-1") ? REGION : 0);
switch(comb) {
     case 0:       /* none are true. */ break;
     case REGION:  /* only regionId is -1 */ break;
     // more combinations.
     case KEY + SEGMENT + REGION: /* all are -1 */ break;
}
like image 21
Peter Lawrey Avatar answered Dec 06 '22 10:12

Peter Lawrey