- 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.
- 程序員面試筆試寶典(第3版)
- Java Web開發(fā)之道
- C語言從入門到精通(第4版)
- Oracle Exadata專家手冊
- Learning Concurrency in Kotlin
- 深入剖析Java虛擬機(jī):源碼剖析與實例詳解(基礎(chǔ)卷)
- 計算機(jī)應(yīng)用基礎(chǔ)教程(Windows 7+Office 2010)
- Unity 3D腳本編程:使用C#語言開發(fā)跨平臺游戲
- Oracle Data Guard 11gR2 Administration Beginner's Guide
- 跟戴銘學(xué)iOS編程:理順核心知識點(diǎn)
- Scrapy網(wǎng)絡(luò)爬蟲實戰(zhàn)
- Practical Maya Programming with Python
- Python應(yīng)用與實戰(zhàn)
- JavaEE架構(gòu)與程序設(shè)計
- 產(chǎn)品架構(gòu)評估原理與方法