Grouping objects by a property and storing them into a map is a challenge that all developers have faced at some point in time. For example, you may have a collection of Customers and you wish to find out which Customers live in each city. Basically, you want a map where City is the key and a Collection of Customers associated with that City is the value.
This was exactly the problem that Kotlin Koans tutorial had me do.
fun Shop.groupCustomersByCity(): Map { // Return a map of the customers living in each city return customers.groupBy { it.city } }
I was able to arrange all of the Customers by city with just one line of Kotlin code. The related Java code wasn’t that difficult either, but I did have to search for the solution since it wasn’t quite as clear as the Kotlin approach.
public static Map groupCustomersByCity(Shop shop){ return shop.getCustomers().stream().collect(Collectors.groupingBy(Customer::getCity)); }
What helped me with the Kotlin approach was that since the groupBy method was direclty on the Collection object, my IDE was able to supply me with the groupBy method. That’s not the case with the Java approach since it’s using a static method on the Collectors class. It also didn’t occur to me to use the collect method on the Stream object either. I was looking for something that said group in it.
You can click here to see Part 19.
One thought on “Kotlin Koans—Part 20”