-1
enum MYOPTIONS {
   OPTION1,OPTION2,OPTION3 .....OPTION100
}

class test {
JSONObject obj = new JSONObject(jsonString);
   public void checkAndAddEnumToList(){
    if(listA.contain(MYOPTIONS.OPTION1.toString())){
 map.add(MYOPTIONS.OPTION1.toString(),obj.getJSONArray(MYOPTIONS.OPTION1.toString()));
   } else if(listA.contain(MYOPTIONS.OPTION2.toString())){
       map.add(MYOPTIONS.OPTION2.toString(),obj.getJSONArray(MYOPTIONS.OPTION2.toString()));
   }else if(listA.contain(MYOPTIONS.OPTION3.toString())){
      map.add(MYOPTIONS.OPTION3.toString(),obj.getJSONArray(MYOPTIONS.OPTION3.toString()));
   }
  }
}

I have OPTION1 to OPTION100, Anyway to avoid If-Else and use REGEX with Loop? Above is just a sample. I am looking to replace IF-ELSE with regex

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • `for` option 1 to 100? – fantaghirocco Nov 25 '19 at 14:20
  • yes. I dont want 100 IF-ELSE blocks If condition based on OPTION{1-100} and setValue also same OPTION{1-100} – user3079153 Nov 25 '19 at 14:22
  • seems like it would be much easier to have an ArrayList of options and iterate through that, and adding the "found" element from list A to list B – sleepToken Nov 25 '19 at 14:25
  • You should iterate `MYOPTIONS.values()`. Though it would probably be more efficient to actually iterate `listA`, parse each value with `MYOPTIONS.valueOf()`, and add it if the parse succeeded. – RealSkeptic Nov 25 '19 at 14:26
  • Possible duplicate of [A for loop to iterate over an enum in Java](https://stackoverflow.com/questions/1104975/a-for-loop-to-iterate-over-an-enum-in-java). – LHCHIN Nov 26 '19 at 04:58

1 Answers1

0

For enums you can use valueOf() and in Java 8+ use streams (or iterate through the list).

public List<MYOPTIONS> checkAndAddEnumToList(List<String> listA) {
    List<Enums.ProfileVisibility> listB = new ArrayList<>();
    listA.stream().forEach(i -> listB.add(Enums.ProfileVisibility.valueOf(i)));
    return listB;
}
Radovan
  • 41
  • 2