Is there a faster way to match an arbitrary String to month name in Java

I want to determine if a string is the name of a month, and I want to do this relatively quickly. The function that is currently stuck in my brain looks something like this:

boolean isaMonth( String str ) {
    String[] months = DateFormatSymbols.getInstance().getMonths();
    String[] shortMonths = DateFormatSymbols.getInstance().getShortMonths();
    int i;

    for( i = 0; i<months.length(); ++i;) {
        if( months[i].equals(str) ) return true;
        if( shortMonths[i].equals(str ) return true;
    }
    return false;
}

However, I will process a lot of text, passing one line at a time for this function, and most of the time I get the worst case of going through the whole loop and returning false.

I saw another question that spoke of regular expression to match the monthly name and the year that could be adapted for this situation. Will regex be faster? Is there any other solution that could be faster?

+5
3

HashSet? , , .

import java.util.HashSet;
import java.util.Collections;
import java.text.DateFormatSymbols;

class Test {
  public static void main(String[] args) {

    HashSet<String> months = new HashSet<String>(24);  

    Collections.addAll(months, DateFormatSymbols.getInstance().getMonths());
    Collections.addAll(months, DateFormatSymbols.getInstance().getShortMonths());

    System.out.println(months.contains(args[0]));

  }
}
+3

shortMonths . Set (HashSet) contains. , .

, (HashMap) , .

+1

HashSet - , , . - jfmasond - , HashSet, , " " .

- - switch, . , , a s, unicode ( UTF-8 ).

, , 2 - , , .

PS - , , , .

+1
source

All Articles