TreeMap Tutorials

From Progzoo
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
  • The key value is the name of a country, the value in each case is an object representing the country:
Algeria(name:'Algeria',region:'Middle East',area:2400000sqkm,pop:32900000,gdp:75012000000)

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]