Course contentsShow
← Java
Lesson 1563 of 2,87034. Collectors in DepthFree lesson

Handling Non-String Stream Elements with joining()

How joining() implicitly calls toString() on stream elements and best practices for mapping to strings first.

Handling Non-String Stream Elements with joining()

You'll learn how joining() automatically converts non-string objects to strings and why explicit mapping is the better practice.

The Implicit Conversion

When you use Collectors.joining() on a stream of non-string elements, Java doesn't complain—it simply calls toString() on each object automatically. While this works, it's not the clearest or most maintainable approach.

List<Integer> numbers = List.of(1, 2, 3, 4, 5);

// This works, but relies on implicit toString() calls
String result = numbers.stream()
    .collect(Collectors.joining(", "));
// Result: "1, 2, 3, 4, 5"

The collector silently invokes Integer.toString() on each element. If you have custom objects, it will call their overridden toString() method—or worse, use the default Object.toString() if none exists.

Best Practice: Explicit Mapping

Always map to strings explicitly before using joining(). This makes your intent crystal clear and gives you full control over the string representation:

List<Integer> numbers = List.of(1, 2, 3, 4, 5);

String result = numbers.stream()
    .map(String::valueOf)  // Explicit conversion
    .collect(Collectors.joining(", "));
// Result: "1, 2, 3, 4, 5"

For custom objects, use a proper mapping function:

people.stream()
    .map(person -> person.getName())  // Explicit field extraction
    .collect(Collectors.joining(", "));

This approach prevents surprises when toString() returns unexpected formats, handles null values more predictably, and documents exactly which property or representation you're joining.

Key Takeaway: While joining() implicitly calls toString() on non-string elements, always use explicit map() transformations first to control string conversion and improve code clarity.