You need to sign in to do that
Don't have an account?
PamSalesforce
If condition in apex
I want to write an if statement like
if( x==1||x==2||x==3){}
Is it possible to write it like
if(x in [1,2,3]){}
or something similar...
if yes,please let me know how....
Thanks,
There is a concept that you can use to perform this type of test. For example:
if(new Set<Integer>{1,2,3}.contains(x)) { // this is equal to if(x==1||x==2||x==3) }
The idea is that you first create an anonymous Set, pre-populated with the conditions to check for, then use the contains instance method to compare a value you are looking for. This trivial example is actually longer than using the original code, but if you had a set of 50 values (a list of states in the United States, for example), this construct would be far more efficient. Strings are particularly efficient using this method:
if(new set<string>('red;green;blue;yellow;white;black;orange' .split(';') .contains(favoriteUserColor)) { // Same as // if( favoriteUserColor=='red' || favoriteUserColor=='green' || favoriteUserColor=='blue' || favoriteUserColor=='yellow' || favoriteUserColor=='white' || favoriteUserColor=='black' || favoriteUserColor=='orange') }
All Answers
I wish there was something like that in Apex...
Thanks for the help.
There is a concept that you can use to perform this type of test. For example:
if(new Set<Integer>{1,2,3}.contains(x)) { // this is equal to if(x==1||x==2||x==3) }
The idea is that you first create an anonymous Set, pre-populated with the conditions to check for, then use the contains instance method to compare a value you are looking for. This trivial example is actually longer than using the original code, but if you had a set of 50 values (a list of states in the United States, for example), this construct would be far more efficient. Strings are particularly efficient using this method:
if(new set<string>('red;green;blue;yellow;white;black;orange' .split(';') .contains(favoriteUserColor)) { // Same as // if( favoriteUserColor=='red' || favoriteUserColor=='green' || favoriteUserColor=='blue' || favoriteUserColor=='yellow' || favoriteUserColor=='white' || favoriteUserColor=='black' || favoriteUserColor=='orange') }