Assume myHashSet = HashSet<SomeClass>
where SomeClass.hashcode() = someField.hashcode()
How can I return an element with the specified hashcode, i.e:
myHashSet.getElementWithHashCode((other as SomeClass).someField.hashcode())
other
and the objects inside the HashSet
are different objects with different property values except someField
value. In other words, these two different type of objects have a common field that might have the same value.
It is weird that there is no such function in HashSet. No one needed that before? What is the quickest way around?
I don't know whether this could you in your case, it would depends on whether it used hashCode
or equals
internally. Some sources online that have a similar problem are looking for an equals-based solution.
Anyway, you can use built-in functions like find
or first
to implement it yourself:
fun <E> HashSet<E>.findByHashCode(other: E): E? = firstOrNull { it.hashCode() == other.hashCode() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With