Iterating over a List with multiple Place AddressComponents - Kotlin

Viewed 22

I am receiving a Place Detail (from Google Maps SDK Android) from a specific place. This Place has different Place Details as a Result.

The output is the following:

Place found: AddressComponents{asList=[AddressComponent{name=58, shortName=58, types=[street_number]}, AddressComponent{name=Schwertstraße, shortName=Schwertstraße, types=[route]}, AddressComponent{name=Sindelfingen, shortName=Sindelfingen, types=[locality, political]}, AddressComponent{name=Böblingen, shortName=BB, types=[administrative_area_level_3, political]}, AddressComponent{name=Stuttgart, shortName=Süd, types=[administrative_area_level_2, political]}, **AddressComponent{name=Baden-Württemberg, shortName=BW, types=[administrative_area_level_1, political]}**, AddressComponent{name=Deutschland, shortName=DE, types=[country, political]}, AddressComponent{name=71065, shortName=71065, types=[postal_code]}]}

I am looking for the specific information of the typ=administrative_area_level_1 and level_2. But i am not able to find a way of iteration.

With Kotlin i am able to access values hard, but this is not the solution. The Objects AddressComponent change their posisitions in new requests to Google Place API. Even some places do only provide less information.

System.out.println(place.addressComponents?.asList()?.get(5)?.name)
System.out.println(place.addressComponents?.asList()?.get(5)?.shortName)

Results in:

Baden-Württemberg
BW

So how can i access the PlaceResult without hard-coding the positions, ignoring the order and find the specific information i am looking for?

1 Answers

The functionality that you're looking for is collections filtering. Assuming your list is named place, the following will return the two matching rows:

val desiredTypes = setOf("administrative_area_level_1",
                         "administrative_area_level_2")  
println(place.filter { it.types.any(desiredTypes::contains) } )
// Prints: [name=Stuttgart, shortName=Süd, types=[administrative_area_level_2, political], name=Baden--Württemberg, shortName=BW, types=[administrative_area_level_1, political]]

The filter function returns any matching elements. it is the (default) name of the element under consideration. The any function returns whether the types sub-element for each element contains any of the items in the desiredTypes set.

Related