官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 乌拉特中旗| 榕江县| 陕西省| 四平市| 沛县| 瑞金市| 平阳县| 周宁县| 宣恩县| 醴陵市| 张家口市| 永吉县| 水富县| 大冶市| 应城市| 宿松县| 大兴区| 札达县| 白河县| 老河口市| 无为县| 江华| 保山市| 宿迁市| 庄浪县| 深泽县| 临澧县| 乌兰察布市| 清镇市| 五台县| 方城县| 深水埗区| 苏尼特右旗| 阳春市| 阜城县| 南乐县| 嵩明县| 凤阳县| 麻城市| 夏邑县| 明星|