How do I create a HashSet of unique values without comparison in Java

Viewed 157

I have a complex Java Bean with ~20 attributes. In my business logic, I am generating around 10^5 unique instances of this Bean.

The bean has a complex and performance costly equals method.

My API signature is old and I can return the data only in a HashSet data structure.

I require to generate this HashSet from the unique instances without invoking the equals method of the bean to have the flow optimized.

Is it possible?

It is guaranteed, the data to be inserted in HashSet are unique beforehand.

1 Answers

IdentityHashMap uses == instead of equals() to compare keys when two of them have the same hash code.

You can create a set from it:

Set<E> set = Collections.newSetFromMap(new IdentityHashMap<>());
Related