- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 233字
- 2021-07-02 19:01:58
String collectors
The string concatenation example can be written using the collector as follows:
//String Concatenation using non parameterized joining
String concatedString = streamSupplier.collect(Collectors.joining());
The factory method joining() will concatenate all the string elements of the stream into a string. There are other overloaded joining() methods, one accepting a delimiter to separate each element of the concatenated string. This comes in handy while generating special delimited text files such as CSVs:
//String Concatenation using joining with delimiter parameter
String delimitedString = streamSupplier.collect(Collectors.joining(","));
The joining() function also has an overloaded function with three parameters, which are delimiter, prefix, and suffix. The overloaded method has been designed in such a way that the developer does not need to worry about the element being iterated in the stream. The method smartly appends a suffix in the end instead of the delimiter:
//String Concatenation using joining with delimiter parameter
String concatString = streamSupplier.collect(Collectors.joining(",","[","]"));
The joining() method not only provides the simplest optimized way to concatenate the strings, but high performance as well. As you will notice the strings can be concatenated using the reduce() method as well, but strings are immutable and hence accumulators concatenating strings tend to copy the string each time. While one can also use the forEach() method along with a Lambda function to append the StringBuffer or StringBuilder, all these options do not perform as well as the joining() method of the collectors.
- Embedded Linux Projects Using Yocto Project Cookbook
- Learning Cython Programming
- DevOps with Kubernetes
- Python自動化運維快速入門(第2版)
- Learning SQLite for iOS
- PySide 6/PyQt 6快速開發與實戰
- HTML 5與CSS 3權威指南(第3版·上冊)
- Python3.5從零開始學
- Spring Security Essentials
- Mastering OpenStack
- 高性能PHP 7
- JavaScript Concurrency
- MongoDB Cookbook
- C++從零開始學(視頻教學版)(第2版)
- Image Processing with ImageJ(Second Edition)