TreeMap Tutorials
Jump to navigation
Jump to search
A TreeMap relates keys to values. Often the keys are Strings and the values are more complex objects.
- In these examples, the TreeMap world is of type TreeMap<String,Country>.
- The data is read from a text file http://progzoo.net/bbc.txt
- The key value is the name of a country, the value in each case is an object representing the country:
Key | Value |
---|---|
Afghanistan | (name:'Afghanistan',region:'Asia',area:652225sqkm,pop:26000000,gdp:0) |
Albania | (name:'Albania',region:'Europe',area:28728sqkm,pop:3200000,gdp:6656000000) |
Algeria | (name:'Algeria',region:'Middle East',area:2400000sqkm,pop:32900000,gdp:75012000000) |
Andorra | (name:'Andorra',region:'Europe',area:468sqkm,pop:64000,gdp:0) |
Angola | (name:'Angola',region:'Africa',area:1250000sqkm,pop:14500000,gdp:14935000000) |
... | |
Zambia | (name:'Zambia',region:'Africa',area:752614sqkm,pop:11000000,gdp:4950000000) |
Zimbabwe | (name:'Zimbabwe',region:'Africa',area:390759sqkm,pop:12900000,gdp:6192000000) |
Contents
Access a value: get
You can access a specific value using get
If you know the name of a country (the key) you can access the associated value.
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]
Missing keys: get
If you try to get a key that is missing it will return null.
The null object is returned of the value is missing.
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]
Testing keys: containsKey
You can check to see if a key exists using containsKey
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]
Adding an entry: put
You can create a new entry using put. You must give the key and the value.
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]
Iterating over the keys: keySet()
You can run over all of the keys using the keySet() method.
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]
Iterating over the values: values()
You can run over all of the values using the values() method.
[Font]
[Default]
[Show]
[Resize]
[History]
[Profile]