Last Updated: July 17, 2023
·
357.7K
· malteo

Joining Objects into a String with Java 8 Stream API

You can leverage Java 8 Collectors to concatenate some objects into a string separated by a delimiter:

For example:

List<Integer> numbers = Arrays.asList( 4, 8, 15, 16, 23, 42 );
return numbers.stream()
        .map( n -> n.toString() )
        .collect( Collectors.joining( "," ) );

will return "4,8,15,16,23,42".

Here's a static function for your Utils class:

public static String join( Collection collection, String delimiter )
{
    return collection.stream()
            .map( Object::toString )
            .collect( Collectors.joining( delimiter ) );
}

Yeah, it's bad, but every project has one :)

1 Response
Add your response

One of the basic codes, thanks.

9 months ago ·