copied
copied

Reputation: 151

Compare strings and return different string

I have a problem, but no solution for now. What i have is around 300 strings for example:

  1. "USNEWYRK";
  2. "USWSHGNT";

And what i have to do is compare if one of these strings are requested string and return something like this:

  1. "USA, New York";
  2. "USA, Washington";

So any good solutions? And i cant use java 1.7. Only 1.6.

Upvotes: 3

Views: 120

Answers (3)

Jon Taylor
Jon Taylor

Reputation: 7905

Create a map of key to value, then just lookup the first value as the key and it will give you the value.

Alternatively you could create an enum, where the enum is the key and the toString of enum is your value.

I would prefer the map solution over the enum myself for this kind of situation.

Example of map

public abstract class LocationHelper {
    public static Map<String, String> locations = new HashMap<String, String>();

    static {
        //either put individual elements into the map or
        //read in from external file etc.
    }
}

In another class you can then get the values by doing the following.

System.out.println(LocationHelper.locations.get("USNWYRK"));

This will print "USA, New York"

Note For anyone unfamiliar with the static { } block this is a static initializer, it is useful for populating static variables like maps. This is different to a insitance initializer { } which is a pre constructor initializer for each instance.

Upvotes: 6

Frederik.L
Frederik.L

Reputation: 5620

You could create a CSV file that contains stringCode;stringValue for easy maintenance, then build up a hash table / map from this file when your application starts.

This would look like :

USNEWYRK;USA, New York
USWSHGNT;USA, Washington

Once these values are mapped it should be easy to return whatever the user needs to know.

Upvotes: 3

Hot Licks
Hot Licks

Reputation: 47729

Any sort of a hash table/map should work. Make the key your first string and the value your second string.

Incidentally, you can enter all your keys and values in a JSON string and use a JSON reader to convert to the map object, vs writing code to enter each one individually.

Upvotes: 0

Related Questions