Java streams 29. Collect 5. String.join() and Collectors.joining()

Terminal operation either returns one value (of the same or another type than the type of the input) or does not return anything at all (produces just side effects). It does not allow another operation to be applied after it and closes the stream.

In this post, we will continue covering the last of the terminal operations called collect():

R collect(Collector<T,A,R> collector)

It allows implementing a vast variety of algorithms using the ready-to-use implementations of collectors created by factory methods of the java.util.stream.Collectors class.



Collectors.joining() is the most popular case of using collect() operation

Once in awhile, we need to create a string that contains comma-separated values. If the values are presented as a fixed set of String values, we can use java.util.StringJoiner class or String.join() method:

     
  StringJoiner joiner = new StringJoiner(", ")
                   .add("cat").add("fish").add("dog");
  System.out.print(str);      //prints: cat, fish, dog

  String string = String.join(", ", "cat", "fish", "dog");
  System.out.print(string);   //prints: cat, fish, dog
     

Alternatively, if the values are collected in an Iterable object, we can use String.join() method:

  
  Iterable<String> list = List.of("cat", "fish", "dog");  
  String str = String.join(", ", list);
  System.out.print(str);      //prints: cat, fish, dog
   

But if the source of the values is a Stream or any other object that can be converted to a Stream, we can use collect() operation with the Collectors.joining() collector (with a parameter that describes a delimiter, which is “, ” in this case):

  
  String str = Stream.of("cat", "fish", "dog")
                     .collect(Collectors.joining(", "));
  System.out.print(str);   //prints: cat, fish, dog
          

If no delimiter is passed in, the values are just concatenated:

  
  String str = Stream.of("cat", "fish", "dog")
                     .collect(Collectors.joining());
  System.out.print(str);   //prints: catfishdog
  

The overloaded version allows adding prefix and suffix to the resulting String value as following:

  
  String str = Stream.of("cat", "fish", "dog")
               .collect(Collectors
                   .joining(", ", "Animals: ", ", and others."));
  System.out.print(str);  
                   //prints: Animals: cat, fish, dog, and others.
   

This way it is definitely easier to do than using the reduce() operation demonstrated in the previous post.

Since Java 8, all collections and many other objects acquired the method that converts them to a Stream, so you can enjoy now this easy way to create a String with comma-separated values.

In the next post, we will continue discussing the collect() operation and show examples of its usage. We will demonstrate how it can be used to create a collection:

Set, using Collectors.toSet() or Collectors.toCollection();

List, using Collectors.toList() or Collectors.toCollection().

See other posts on Java 8 streams and posts on other topics.
You can also use navigation pages for Java stream related blogs:
— Java 8 streams blog titles
— Create stream
— Stream operations
— Stream operation collect()
The source code of all the code examples is here in GitHub

, ,

Send your comments using the link Contact or in response to my newsletter.
If you do not receive the newsletter, subscribe via link Subscribe under Contact.

Powered by WordPress. Designed by Woo Themes