CodexBloom - Programming Q&A Platform

Unexpected behavior when using Java Streams with custom collector in Java 17

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
java streams collectors java-17 Java

I need help solving I'm trying to configure I'm encountering an unexpected behavior when utilizing a custom collector with Java Streams in my Java 17 application. I wrote a collector to group a list of objects based on a specific property, but the output is not as expected. Here's a simplified version of my code: ```java import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } } public class Main { public static void main(String[] args) { List<Person> people = List.of(new Person("Alice", 30), new Person("Bob", 25), new Person("Alice", 22)); Map<String, List<Person>> groupedByName = people.stream() .collect(Collectors.groupingBy(person -> person.name)); System.out.println(groupedByName); } } ``` The output I receive is: ``` {Alice=[Person@1b6d3586, Person@4554617c], Bob=[Person@1b6d3586]} ``` However, I expected the output to show the names correctly keyed with their respective `Person` objects. Instead, it seems to be showing the default `toString()` representation for the `Person` objects. I tried implementing a custom `toString()` method in the `Person` class: ```java @Override public String toString() { return String.format("%s (age: %d)", name, age); } ``` But the output remains the same. I also verified that I am using Java 17 and that my IDE is set up correctly. What could be causing this issue? How can I make sure that the grouping displays the expected values instead of the default object representation? Any insights would be appreciated. Any ideas how to fix this? I recently upgraded to Java 3.9. Thanks for your help in advance!