views:

49

answers:

2

Hi guys,

it may be a nooby question, but I've never needed it before:

I have several strings and I want to compare them to given ones...

At first glance it would lead to a switch/case construction in what every available entry is checked.

Is there a more elegant way to swap those strings as key/value datas?

greets, poeschlorn

+1  A: 

Update: My bad. I misread this as case insensitive search.

Case sensitive is easy. Java does not yet support Strings in switch statements. The easiest solution is:

if (string1.equals(string2)) {
  ...
} else if (string1.equals(string3)) {
  ...
}

Or as a loop:

String[] matches = new String[] {
  "abcd",
  "efgh",
  "ijkl"
};

for (String match : matches) {
  if (matches.equals(string)) {
    ...
  }
}

Of course, this is linear (O(n)) and doesn't scale but is simple and is sufficient for the simplest of cases. A better solution is to use a hash-based lookup:

Set<String> matches = new HashSet<String>();
matches.add("abcd");
matches.add("efgh");
matches.add("ijkl");

if (matches.contains(string1)) {
  ...
}

This is near-linear (O(1)) lookup and will scale much better with a large number of Strings.

cletus
If there are lots of strings, your matching mechanism will be fairly slow -- O(n) -- whereas using a predefined HashSet or HashMap will give an expected O(1) lookup.
Michael Aaron Safyan
+3  A: 

Yes, use the strings as keys in a HashMap, and have the corresponding values be objects defining the action to take if the key has been matched, unless you only have one behavior, in which case you can simply use a HashSet, test if the string is in the set, and then take action accordingly.

Michael Aaron Safyan
Too complicated given the matching is case insensitive unless there is a sufficiently large set of strings to match to justify the complexity.
cletus
@cletus, where does the OP say it needs to be case-insenstive? And if it does need to be case-insensitive, then just use lower-case keys in the map or lower-case values in the set, then convert the input string to lower case before performing the lookup.
Michael Aaron Safyan
@Michael my bad. Misread the question.
cletus