In php, one can handle a list of state names and their abbreviations with an associative array like this:
in java for associative array use Map
import java.util.*;
class Foo
{
public static void main(String[] args)
{
Map<String, String> stateMap = new HashMap<String, String>();
stateMap.put("ALABAMA", "AL");
stateMap.put("ALASKA", "AK");
// ...
stateMap.put("WYOMING", "WY");
for (Map.Entry<String, String> state : stateMap.entrySet()) {
System.out.printf(
"The abbreviation for %s is %s%n",
state.getKey(),
state.getValue()
);
}
}
}
This is the modified code from o948 where you use a TreeMap instead of a HashMap. The Tree map will preserve the ordering of the keys by the key.
import java.util.*;
class Foo
{
public static void main(String[] args)
{
Map<String, String> stateMap = new TreeMap<String, String>();
stateMap.put("ALABAMA", "AL");
stateMap.put("ALASKA", "AK");
// ...
stateMap.put("WYOMING", "WY");
for (Map.Entry<String, String> state : stateMap.entrySet()) {
System.out.printf(
"The abbreviation for %s is %s%n",
state.getKey(),
state.getValue()
);
}
}
}
Along the lines of Alexander's answer...
The native python dictionary doesn't maintain ordering for maximum efficiency of its primary use: an unordered mapping of keys to values.
I can think of two workarounds:
look at the source code of OrderedDict and include it in your own program.
make a list that holds the keys in order:
states = ['Alabamba', 'Alaska', ...]
statesd = {'Alabamba':'AL', 'Alaska':'AK', ...}
for k in states:
print "The abbreviation for %s is %s." % (k, statesd[k])
in Python:
for key, value in stateDict.items(): # .iteritems() in Python 2.x
print "The abbreviation for %s is %s." % (key, value)
in Java:
Map<String,String> stateDict;
for (Map.Entry<String,String> e : stateDict.entrySet())
System.out.println("The abbreviation for " + e.getKey() + " is " + e.getValue() + ".");
Another way of doing it in Java. Although a better way has already been posted, this one's syntactically closer to your php code.
for (String x:stateDict.keySet()){
System.out.printf("The abbreviation for %s is %s\n",x,stateDict.get(x));
}
In python an ordered dictionary is available in Python 2.7 (not yet released) and Python 3.1. It's called OrderedDict.