Skip to main content

Posts

Showing posts with the label collections

Operations on Collections in Kotlin

Collections This post provides some of the operations that can be done in the collections using kotlin The below is the base type definitions that will be used in the below collection queries data class Shop ( val name : String , val customers : List < Customer >) data class Customer ( val name : String , val city : City , val orders : List < Order >) { override fun toString () = " $ name from ${ city . name } " } data class Order ( val products : List < Product >, val isDelivered : Boolean ) data class Product ( val name : String , val price : Double ) { override fun toString () = "' $ name ' for $ price " } data class City ( val name : String ) { override fun toString () = name } Operations on collections // Return a list of customers, sorted in the descending by number of orders they have made fun Shop. getCustomersSortedByOrders (): List<Customer> = this .customers.sortedByDescending( { it -> it.order

Helpful functions from org apache commons collections

Introduction There are times when we are faced with the option to get the intersection of 2 lists. The type of list can be either a simple type like number / strings or a complex type like Object. This might involve developers building loops and performing comparison. This can be resulting in not following the DRY principle where we do not have to repeat ourselves what is already implemented. We can leverage the functionality provided in the collections4 library which can help us get the desired result. In this example, let us consider the following example.  Sample Scenario We can consider a "Cart" store which keeps track of the various items that we have added the cart. Every addition or deletion of the item to the cart needs to be updated. User's normally add some items and when they find out that their product of interest has its availability, they would want to add that to the cart and balance out by removing a lesser priority item. Now, when the user proceeds for th