4ankoku
4ankoku

Reputation: 25

How to group object by value change

so currently my object look like this

data class Country(
    val city: List<City>
)

and this

data class City(
   val prefecture: String,
   val city_code: String,
   val city_name: String
)

The response i got from API is

{"city": [
    {"prefecture": "Aichi",
      "city_code": "OKZ",
      "city_name": "Okazaki"},
    {"prefecture": "Aichi",
      "city_code": "HKN",
      "city_name": "Hekinan"},
    {"prefecture": "Kagoshima",
      "city_code": "AKN",
      "city_name": "Akune"},
    {"prefecture": "Kagoshima",
      "city_code": "HOI",
      "city_name": "Hioki"},
  ]}

What would be a way to group prefecture data by detecting the value change. And the output that i expected look like this

=== Aichi ===
Okazaki, OKZ
Hekinan, HKN

=== Kagoshima ===
Akune, AKN
Hioki, HOI

sorry for my bad english

Upvotes: 1

Views: 195

Answers (1)

youhans
youhans

Reputation: 6839

If you want the exact mentioned output, this can do the job for you:

val country = ObjectMapper().registerModule(KotlinModule()).readValue<Country>(json)

val groupedCities = country.city.groupBy({ it.prefecture }) { it.city_name + ", " + it.city_code }

val output = groupedCities.entries.joinToString("\n\n") { "=== " + it.key + " ===\n" + it.value.joinToString("\n") }
println(output)

Upvotes: 1

Related Questions