Contents Prev: Hello World Next: Using tags: counting businesses

Iterators and readers: counting elements

In this example we will retrieve some data from the Overpass API using a bounding box query. We then iterate all objects in the returned dataset and count the number of nodes, ways and relations we encounter:

Here's the output:

nodes: 898
ways: 71
relations: 20

The OsmIterator extends the standard java.util.Iterator, hence you can also replace the for loop with a while loop if you prefer this style:

Using a reader instead of an iterator

The previous examples used the iterator pattern for accessing our data. As an alternative, osm4j provides OsmReader implementations for all data formats to support callback driven programming out of the box:

Here's a reimplementation of the element counter using callbacks. We define a Counter class that extends the DefaultOsmHandler so that it can be passed to the reader using the setHandler() method:

Contents Prev: Hello World Next: Using tags: counting businesses