I need to store key/value info in some type of collection. In C#, I'd define a dictionary like this:
var entries = new Dictionary<string, int>();
entries.Add("Stop me", 11);
entries.Add("Feed me", 12);
entries.Add("Walk me", 13);
Then I would access the values so:
int value = entries["Stop me"];
How do I do this in Java? I've seen examples with ArrayList
, but I'd like the solution with generics, if possible.
You want to use a Map
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("Stop me", 11);
Integer i = m.get("Stop me"); // i == 11
Note that on the last line, I could have said:
int i = m.get("Stop me");
Which is shorthand for (with Java's auto-unboxing):
int i = m.get("Stop me").intValue()
If there is no value in the map at the given key, the get
returns null
and this expression throws a NullPointerException
. Hence it's always a good idea to use the boxed type Integer
in this case
Use a java.util.Map
. There are several implementations:
HashMap
: O(1) lookup, does not maintain order of keysTreeMap
: O(log n) lookup, maintains order of keys, so you can iterate over them in a guaranteed orderLinkedHashMap
: O(1) lookup, iterates over keys in the order they were added to the map.You use them like:
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Stop me", 11);
map.put("Feed me", 12);
int value = map.get("Stop me");
For added convenience working with collections, have a look at the Google Collections library. It's excellent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With