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 :)
Written by Matteo Giordano
Related protips
1 Response
One of the basic codes, thanks.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#String
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#