Skip to content
Advertisement

How to match equals() and hashCode in streams?

I have a stream where I am aggregating some data like this:

JavaScript

The problem is that by adding this comparator I am braking the contract between hashCode() and equals() and at the end I have duplicate keys:

enter image description here

Has anyone some ideas how can I fix this? Or is there a way to sort the final object ( Map<String, Map<String, Map<EventType, Long>>>) that is returned by the stream after the key of the second map?

My entire map looks like this:

<"Some String",<"2-2022",<"HOLIDAY",2>>>

And I want to sort in asc order after “2-2022”.

Thanks

Advertisement

Answer

Your comparator is broken. Comparators have rules they need to adhere to; one of them is commutativity; if your comparator claims that a is below b, then b must be above a. This isn’t true with your implementation; if a and b are equal, your comparator says that ‘a’ is above ‘b’, and also that ‘b’ is above ‘a’.

Return 0 for equal stuff. Easiest way is to use java’s built in stuff:

JavaScript

Much shorter, much easier to read, and.. correct, which is nice.

NB: equals and hashCode are completely irrelevant here. TreeMap does not invoke or use them in any way; it uses the comparator for everything. The problem was your broken comparator implementation.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement