I have the following code:

    model = MODEL_A;
} else if(PATTERN_B.matcher(someValue).matches()){
    model = MODEL_B;
} else if(PATTERN_C.matcher(someValue).matches()){
    model = MODEL_C;
} else if(PATTERN_D.matcher(someValue).matches()){
    model = MODEL_D;
//  etc... 
} else {
    throw new NoMatchException();

This is very redundant and ugly.

What I'd like is for code like this:

Map<Pattern, String> modelByPatternMap = new Map<Pattern, String>{

Pattern pattern = findPattern(someValue);
model = modelByPatternMap.get(pattern);

Is there any better way to create an efficient implementation of findPattern() than brute force, iterating through the map keys, trial and error?

  • 3
    What are MODEL_A, MODEL_B, etc? What do the expressions actually look like? It seems like you could just use Type.forName here but you haven't given enough context to determine if that is a workable suggestion. – Adrian Larson May 28 '19 at 16:43
  • The type of "model" (which, in the code, you can see is a String) is actually unimportant. The point is only to reverse the normal working of the relationship between a Pattern and some value being matched against it.... Not so dissimilar to how if I have 10 - x = 8, I can flip things around to determine x = 10 - 8, so x must be 2. – Brian Kessler May 29 '19 at 12:29

The for loop would be more efficient (e.g. stops at first match). The only way to avoid a for loop would be to sacrifice performance:

Map<Boolean, String> theMap = new Map<Boolean, String>() {
  pattern_a.matcher(someValue).matches() => model_a,
  pattern_b.matcher(someValue).matches() => model_b,
  pattern_c.matcher(someValue).matches() => model_c,
if(theMap.containsKey(true)) {
  model = theMap.get(true);

The code is "cleaner", but the performance will suffer accordingly. A for-each loop over the keys would be more efficient despite adding a few lines of code.

| improve this answer | |
  • That's a clever approach, but I agree, I think a loop would be better.... I was hoping there could be some native "reverse match" code, but I couldn't fathom what the implementation would be and I expect (if it existed) under the hood it would pretty much need to do the same thing. I'm just going to leave this open for a bit to see if any other interesting answers come up. :-) – Brian Kessler May 28 '19 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.