[Solved] How to define a string array in java and use it in switch case


Trying to enumerate all the different possible strings in the array is generally a bad idea and not the correct way to write your program. Sure your example works, but what would happen if your set of possible strings was not just {‘this’, ‘is’, ‘a’, ‘test’}, but instead had say 10000 elements? What if you didn’t know exactly what String elements were in the array? As a previous user mentioned, you want to use a HashMap<String, Integer>.

String[] arr = yourStringArray; //wherever your Strings are coming from
Map<String, Integer> strCounts = new HashMap<String, Integer>; //this stores the strings you find
for (int i = 0; i < arr.length; i++) {
    String str = arr[i];
    if (strCounts.containsKey(str)) {
        strCounts.get(str) += 1; //if you've already seen the String before, increment count
    } else {
        strCounts.put(str, 1); //otherwise, add the String to the HashMap, along with a count (1)
    }
}

solved How to define a string array in java and use it in switch case