Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get() specific element from HashSet? Kotlin

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?

like image 310
Xfce4 Avatar asked Oct 16 '22 05:10

Xfce4


1 Answers

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() }
like image 101
Malte Hartwig Avatar answered Oct 19 '22 02:10

Malte Hartwig