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

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.

主站蜘蛛池模板: 永靖县| 湟中县| 积石山| 沙雅县| 仲巴县| 商水县| 河池市| 镇平县| 青阳县| 阿城市| 依安县| 特克斯县| 东光县| 昌平区| 岚皋县| 晋江市| 三都| 南昌市| 西丰县| 宜宾市| 仁怀市| 抚松县| 泸西县| 当涂县| 平顶山市| 阿拉善左旗| 镇安县| 玉门市| 铜山县| 扎囊县| 玉田县| 上虞市| 彭州市| 吴旗县| 民勤县| 宁波市| 寿宁县| 上高县| 遂平县| 阜城县| 平阴县|