Java 8 Stream API: How to maintain order while removing duplicates from a List of Custom Objects?
I tried several approaches but none seem to work. Hey everyone, I'm running into an issue that's driving me crazy. After trying multiple solutions online, I still can't figure this out. I'm trying to debug I'm working with a List of custom objects in Java 8, and I'm trying to remove duplicates while maintaining the original order of the elements. The custom class is `Person` with fields `name` and `age`. I've attempted to use the `Stream` API and `distinct()`, but it seems to only check for object reference equality rather than my defined equality logic. Hereโs what Iโve tried: ```java import java.util.*; import java.util.stream.*; class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Person)) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } } public class Main { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("Alice", 30), new Person("Bob", 25), new Person("Alice", 30), new Person("Charlie", 35) ); List<Person> distinctPeople = people.stream() .distinct() .collect(Collectors.toList()); distinctPeople.forEach(p -> System.out.println(p.name + " " + p.age)); } } ``` This code returns three `Person` objects, but I expected just two. The output is: ``` Alice 30 Bob 25 Alice 30 Charlie 35 ``` I have also considered using a `LinkedHashSet` to maintain order, but Iโm unsure how to integrate that with a stream. How can I achieve this? Whatโs the best practice for maintaining the order while ensuring duplicates are removed based on specific fields in my custom object? This is my first time working with Java latest. Any suggestions would be helpful. Could this be a known issue? I recently upgraded to Java 3.9. Has anyone else encountered this? The stack includes Java and several other technologies. I'd be grateful for any help.