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

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.

主站蜘蛛池模板: 泸溪县| 岫岩| 临汾市| 延川县| 灌阳县| 四平市| 甘孜| 瑞安市| 光山县| 林西县| 莆田市| 凤城市| 蒙城县| 浦县| 双柏县| 商河县| 清河县| 桂平市| 新化县| 义乌市| 图木舒克市| 霍城县| 建瓯市| 柞水县| 屯门区| 黄龙县| 卓资县| 方正县| 松溪县| 泸溪县| 会泽县| 洪泽县| 苏尼特右旗| 渭南市| 墨竹工卡县| 资溪县| 宜宾市| 白城市| 三江| 博乐市| 古交市|