0

I am trying to learn some kotlin since most of Android development is moving to the kotlin language. I have a sample code that I was trying to solve in kotlin

class City(val country: String, val name: String, val population: Int)

fun main(args: Array<String>) {
  val cities = arrayOf<City>(
    City(country = "USA", name = "Boston", population = 2500000000),
    City(country = "China", name = "Beijing", population = 100000000),
    City(country = "USA", name = "Atlanta", population = 6000300)
  )

  printCitiesByCountry(cities);

I need to write a function printCitiesByCountry(cities) that returns sample :

  • USA = [Boston = 250000000, Atlanta = 6000300]
  • China = [Beijing = 100000000]

How can I achieve this.

Maria
  • 377
  • 2
  • 15
  • Sorry to be a pedant, but Africa is a continent, not a country; and Nigeria and Ghana are countries, not cities. And, more relevantly: in Kotlin, arrays are generally used only for backward compatibility; lists are much more common, as they're more flexible. – gidds Jul 10 '20 at 01:51
  • Ha! oh my goodness I am sorry that is indeed a big mistake. – Maria Jul 10 '20 at 01:59

1 Answers1

3

use groupBy:

class City(val country: String, val name: String, val population: Int)

fun main(args: Array<String>) {
  val cities = arrayOf<City>(
    City(country = "Africa", name = "Nigeria", population = 25000000),
    City(country = "China", name = "Beijing", population = 100000000),
    City(country = "Africa", name = "Ghana", population = 6000300)
  )
  
  printCitiesByCountry(cities)
}

fun printCitiesByCountry(cities: Array<City>) {
    val citiesByContinent = cities.groupBy(keySelector={ it.country }, valueTransform={ "${it.name} = ${it.population}" })
    println(citiesByContinent)
}
Mike Delmonaco
  • 314
  • 4
  • 13
  • How would that function look like in Java using for instance Map<> – Maria Jul 11 '20 at 22:32
  • This is what I have so far List c = new ArrayList<>(); c.add(new City("USA", "Boston", 25000000)); c.add(new City("China", "Beijing", 25000000)); c.add(new City("USA", "Atlanta", 25000000)); printCitiesByName(c); – Maria Jul 11 '20 at 22:33
  • @AnnaMurray I don't understand exactly what you mean. If you want to do this in Java, you'd need to implement something similar to groupBy in Java. A Map> would be a good way to go about it. Here is an example of doing that: https://stackoverflow.com/questions/21678430/group-a-list-of-objects-by-an-attribute-java – Mike Delmonaco Jul 12 '20 at 01:58