Course contentsShow
← Java
Lesson 1449 of 2,87032. Streams API: Intermediate OperationsFree lesson

Using distinct with Custom Objects

Learn the critical importance of proper equals() and hashCode() implementations for distinct to work correctly.

Using distinct with Custom Objects

You'll learn why distinct() may not work as expected on custom objects without proper setup.

So far, you've seen distinct() remove duplicates from streams of strings or numbers. But when you use distinct() with your own custom classes, you might be surprised to find it doesn't work at all—duplicate objects still appear in the output!

Why distinct Needs equals() and hashCode()

The distinct() operation relies on object equality to identify duplicates. By default, Java compares objects by their memory address (reference equality), meaning two Person objects with identical names and ages would still be considered different.

To fix this, you must override two methods in your custom class:

  • equals(Object obj) – defines when two objects are "the same"
  • hashCode() – returns an integer code used for efficient duplicate detection

Think of it like a library system: hashCode() is the shelf number (quick lookup), and equals() is checking if two books are actually the same title. You need both for the system to work correctly.

The Contract

These methods must follow a contract:

  • If a.equals(b) is true, then a.hashCode() must equal b.hashCode()
  • Objects that are equal must always return the same hash code

Without proper implementations, distinct() treats every instance as unique, even if you consider them duplicates based on their field values.

Why It Matters

When streaming collections of Person, Product, or any domain object, distinct() silently fails without these overrides. The stream appears to work, but duplicates slip through because Java can't tell which objects are "the same."

Key Takeaway: For distinct() to work with custom objects, you must override equals() and hashCode() according to their contract—otherwise, every instance is treated as unique regardless of field values.