0

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

2 Answers 2

3

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.

2
  • Too complicated given the matching is case insensitive unless there is a sufficiently large set of strings to match to justify the complexity.
    – cletus
    Jun 1, 2010 at 8:31
  • @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. Jun 1, 2010 at 9:45
1

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.

1
  • 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. Jun 1, 2010 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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