This part of Kotlin Koans continues to build on the features Kotlin offers on collection. Most of these methods will look familiar to people who have worked with Java 8 streams.
In this portion of the tutorial, I had to work with the maxBy method. It’s a nice little shortcut method to find an item based on a property. There is also a companion minBy.
fun Shop.getCustomerWithMaximumNumberOfOrders(): Customer? { // Return a customer whose order count is the highest among all customers return customers.maxBy { it.orders.size } } fun Customer.getMostExpensiveOrderedProduct(): Product? { // Return the most expensive product which has been ordered return orderedProducts.maxBy { it.price } }
I was curious about what it would take to solve this problem in Java. Here is what I came up with.
public static Optional getCustomerWithMaximumNumberOfOrders(Shop shop){ return shop.getCustomers().stream().max(Comparator.comparingInt(lhs -> lhs.getOrders().size())); }
I can’t say it was too brutal, but I think maxBy
is much easier to read and understand as opposed to stream().max(Comparator.comparingInt(lhs -> lhs.getOrders().size()))
You can click here to see Part 16
One thought on “Kotlin Koans—Part 17”