Hildebrandt Tobias
07/03/2024, 1:03 PMfun <T, K> List<T>.intersectBy(new: List<T>, keySelector: (K)): List<T> =
map { keySelector to it }
.intersect(new.map { keySelector to it }.toSet())
.map { (_, value) -> value }
Sam
07/03/2024, 1:13 PMkeySelector
supposed to be (T) -> K
?Sam
07/03/2024, 1:23 PMHildebrandt Tobias
07/03/2024, 1:47 PM(T) -> K
.
Now I can't remember what I exactly wanted to achieve in the first place
and I am now at
fun <T, K> List<T>.intersectBy2(new: List<T>, keySelector: (T) -> K): List<K> =
map { keySelector(it) }
.intersect(new.map { keySelector(it) }.toSet())
.toList()
I just wanted a generic way to tell me the changed...
OH now I remember lol. I didn't just want to get the IDs of the changed entries.
That was the reason I put it in a Pair.
So changedBy()
might be more appropriate.
I should have been more verbose in my question and not give in to Meeting pressure or just do it after.
Quick correction:
fun <T, K> List<T>.changedBy(new: List<T>, keySelector: (T) -> K): List<K> {
val old = this.associateBy { keySelector(it) }
val newed = new.associateBy { keySelector(it) }
val changed = old.filter { (key, value) -> newed[key]?.let { it != value } == true }
val result = changed.keys.toList()
return result
}
edit: and updated:
fun <T, K> List<T>.changedBy(new: List<T>, keySelector: (T) -> K): List<K> =
associateBy { keySelector(it) }
.let { old -> new
.associateBy { keySelector(it) }
.filter { (key, value) -> old[key] == value }
.keys
.toList()
}
Daniel Pitts
07/03/2024, 2:42 PMold[key] != value
? Looks like your selecting the keys where the values are the same between the two lists.Daniel Pitts
07/03/2024, 2:45 PMfun <T, K> List<T>.changedBy(new: List<T>, keySelector: (T) -> K): List<K> =
(new - this.toSet()).map(keySelector)
Daniel Pitts
07/03/2024, 2:46 PMtoSet()
, it assumes hashCode is implemented correctly.Hildebrandt Tobias
07/04/2024, 8:54 AMold[key] != value
.
I tried your solution, but it also carries over new values that have not been in the list before.
As an example from these two lists (assume Pairs) [(1, "old1"), (2, "old2"), (3, "old3")]
and [(2, "old2"), (3, "new3"), (4, "new4")]
The call old.changedBy(new) { it.first }
should only output [3]
, your's gives [3, 4]
.Daniel Pitts
07/04/2024, 2:20 PM