Alpesh Vas
11/07/2019, 7:06 PMXavier F. Gouchet
11/07/2019, 7:39 PMkarelpeeters
11/07/2019, 8:46 PMAlpesh Vas
11/08/2019, 8:00 AMAlpesh Vas
11/08/2019, 8:02 AMdata class Customer(
val id: Int,
val name: String,
val phoneNumber: String
)
val customerIds = listOf(1, 2, 3, 4, 5)
val customers = listOf(
Customer(id = 0, name = "Alpesh", phoneNumber = "019"),
Customer(id = 2, name = "Vas", phoneNumber = "245"),
Customer(id = 3, name = "Alp3", phoneNumber = "678"),
Customer(id = 6, name = "Alp4", phoneNumber = "901"))
Let say, now I want to find intersection of customers
array and customerIds
and return list of Customer
after intersection.Alpesh Vas
11/08/2019, 8:05 AM/**
* Returns a set containing all elements that are contained by both this set and the specified collection.
*
* The returned set preserves the element iteration order of the original collection.
*/
public infix fun <T> Iterable<T>.intersect(other: Iterable<T>): Set<T> {
val set = this.toMutableSet()
set.retainAll(other)
return set
}
We can't use this function as types of both iterables are different in our case. We need some transform function here.Alpesh Vas
11/08/2019, 8:06 AMfun <T, A> Iterable<A>.intersect(other: Iterable<T>, valueTransform: (A) -> T ): List<A> {
val set = this.map(valueTransform).toMutableSet()
set.retainAll(other)
return this.filter {valueTransform(it) in set}
}
Alpesh Vas
11/08/2019, 8:07 AMval customerAfterInterSection = customers.intersect(customerIds){it.id}
Alpesh Vas
11/08/2019, 8:08 AMAlpesh Vas
11/08/2019, 8:11 AMXavier F. Gouchet
11/08/2019, 8:24 AMval customerAfterIntersect = customers.filter { it.id in customerIds }
Alpesh Vas
11/08/2019, 8:44 AMit.id in customerIds
is not efficient operation here right?Alpesh Vas
11/08/2019, 8:44 AMXavier F. Gouchet
11/08/2019, 8:45 AMXavier F. Gouchet
11/08/2019, 8:46 AMAlpesh Vas
11/08/2019, 8:47 AMAlpesh Vas
11/08/2019, 8:47 AMO(n)
whilst set does it in O(1)
Alpesh Vas
11/08/2019, 1:08 PMnkiesel
11/08/2019, 2:23 PMval customerAfterIntersect = customers.filter { it.id in customerIds.toSet() }
gildor
11/08/2019, 2:47 PMgildor
11/08/2019, 2:48 PMAlpesh Vas
11/08/2019, 5:56 PMgildor
11/09/2019, 12:31 AMDerek Peirce
11/09/2019, 5:19 AMvalueTransform
on each element twice, which is fine if it is cheap, but problematic if it is expensive and has side-effects.Fudge
11/11/2019, 12:26 AMwhat abouttoSet needs to go outside the loop or it will spend o(n) time making the set every loopval customerAfterIntersect = customers.filter { it.id in customerIds.toSet() }
Alpesh Vas
11/11/2019, 5:16 AM