- 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.
- C++面向對象程序設計(第三版)
- Mastering RabbitMQ
- Mastering JavaScript Object-Oriented Programming
- ASP.NET Core 5.0開發入門與實戰
- Learning RxJava
- 零基礎學Java程序設計
- 面向對象程序設計(Java版)
- The HTML and CSS Workshop
- 大學計算機基礎實驗指導
- Corona SDK Mobile Game Development:Beginner's Guide(Second Edition)
- Learning OpenStack Networking(Neutron)(Second Edition)
- Orleans:構建高性能分布式Actor服務
- Programming Microsoft Dynamics? NAV 2015
- C語言程序設計
- Arduino機器人系統設計及開發