I have a list of objects. Some are similar to each...
# getting-started
d
I have a list of objects. Some are similar to each other and I'd like to merge those ones together. There's no object key - the similarity is fuzzy (I have the algorithm for comparing two objects already). Are there any list methods that would help me here? Or does it have to be done procedurally, rather than functionally? Maybe a better question is, can I create a grouping based on comparing objects, rather than by using a keyfinder? Sorry if wrong channel, I'll happily move to another one but wasn't sure where to ask.
j
You could build a custom key class out of your object and override equality of that class to represent your similarity algorithm:
Copy code
list.groupBy { MyKey(it) } // or groupingBy + aggregate

class MyKey(val obj: MyObj) {
    override fun equals(other: Any): Boolean {
        // return true if similar
    }
    override fun hashCode(): Int = ...
}
A bit farfetched but it would work I believe.
d
that's pretty overengineered i love it, thank you
it's also a perfect answer to my question and possibly the simplest way to use Grouping for this
j
It is indeed a bit overengineered 😅 If somehow you can derive a real key out of the properties of your objects it would be better of course
d
that would be ideal, but it's user-submitted freeform data lol
e
your equivalence classes being non-transitive could be problematic though
e.g. if a ≈ b, b ≈ c, a ≉ c, what would you do?
d
hm yeah, maybe i should just do a regular nested loop to create a 2d list of similar objects
and then run a reduce on that to merge
performance isn't important for this scenario, it runs once a day in a cronjob