dsk
dsk

Reputation: 657

Switch case with multiple values

Is there something like array of case statement and put it as single case statement into switch- suppose

String[] statements={"height","HEIGHT"};

and then

switch(code){
 case statements: 
  //code here
  break;
 case something_else:
  break;
}

so if we add values into String array then it will automatically matched from that array in switch? like

  var1||var2||whatever //accessed from array or anything else for matching

is there any implementation similar like this?

Upvotes: 5

Views: 23525

Answers (5)

Prectron
Prectron

Reputation: 465

Switch statements and expressions (available since Java SE 14) don't support matching values from an array. For such cases, the construct you are looking for is a chain of if, else if, and else. You can use Stream to easily check if an array contains a given element.

private boolean contains(String[] array, String value) {
    return Arrays.stream(array).anyMatch(value::equals);
}
if (contains(statements, code)) {
    // do something with a code
} else if(contains(otherStatements, code)) {
    // do something with another code
} else {
    // do something with other codes
}

Upvotes: 0

Eddy
Eddy

Reputation: 76

According to the Java Documentation:

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

Unless you can boil your data down to one of these, that's all you can use. You can always break out what you would have in the statement array, but you wouldn't be able to make switch dynamic using an array.

Upvotes: 0

HamoriZ
HamoriZ

Reputation: 2438

You can remove the break to get OR

switch(code){
 case case1:   
 case case2:
    doSomething();
  break;
}

Upvotes: 10

Codebender
Codebender

Reputation: 14471

switch case statements don't break unless you specifically ask it to.

Hence for your case, you can use this as a work around,

switch(code){
 case "height":
 case "HEIGHT": 
 case "weight":
  //code here
  break;
 case something_else:
  break;
}

Upvotes: -1

Bgvv1983
Bgvv1983

Reputation: 1256

I think I wouldn't youse a switch in this case. I would do probably something like this

if(Arrays.asList(yourArray).contains(yourValue)){
   //do something
}else{
   //do something else
}

Upvotes: 2

Related Questions