im4lja
Last Updated: November 21, 2017
·
18.37K
· malteo
D19108207d7ebfd0e18e4a7108c5d656

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 :)

Say Thanks
Respond