koufa
02/09/2018, 1:22 PMclass A(val name: String, val country: String)
class B(val name: String, val age: Int)
class C(val name: String, val age: Int, val country: String)
What is the idiomatic way in Kotlin to combine two lists say List<A>
and List<B>
to a new List<C>
if C
is produced from A and B
if a.name == b.name
?kristofdho
02/09/2018, 1:31 PMdiesieben07
02/09/2018, 1:32 PMval a = listOf<A>()
val b = listOf<B>()
val c = a.zip(b)
.filter { (a, b) -> a.name == b.name}
.map { (a, b) -> C(a.name, b.age, a.country) }
kristofdho
02/09/2018, 1:34 PMdiesieben07
02/09/2018, 1:35 PMkoufa
02/09/2018, 1:35 PMdiesieben07
02/09/2018, 1:37 PMgroupBy
then, get the set of shared keys of the two resulting maps, then combinekristofdho
02/09/2018, 1:45 PMfun toC(a: List<A>, b: List<B>): List<C> {
val names = a.map(A::name).union(b.map(B::name))
val aa = a.filter { names.contains(it.name) }.sortedBy(A::name)
val bb = b.filter { names.contains(it.name) }.sortedBy(B::name)
return aa.zip(bb).map { (a, b) -> C(a.name, b.age, a.country) }
}
bloder
02/09/2018, 1:48 PMval listA = listOf(1, 2, 3, 4, 5)
val listB = listOf(1, 2, 6, 7, 5)
val listC = mutableListOf<Int>()
listA.fold(listB) { acc, i -> if (acc.contains(i)) listC.add(i); acc }
print(listC) // [1, 2, 5]
kristofdho
02/09/2018, 1:52 PMfun toC2(a: List<A>, b: List<B>): List<C> {
val aa = a.associateBy(A::name)
val bb = b.associateBy(B::name)
return aa.keys.union(bb.keys).map {
C(it, bb[it]!!.age, aa[it]!!.country)
}
}
pitty of the ugly !!
Andreas Sinz
02/09/2018, 1:56 PMlistA.mapNotNull { a ->
listB.firstOrNull { b -> a.name == b.name }
?.let { b -> C(a. name, b. age, a.country) }
}
kristofdho
02/09/2018, 1:59 PMAndreas Sinz
02/09/2018, 2:02 PMkristofdho
02/09/2018, 2:05 PMkoufa
02/09/2018, 2:06 PMjuhanla
02/09/2018, 2:10 PM