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

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.

主站蜘蛛池模板: 克什克腾旗| 扶绥县| 乐昌市| 阿拉尔市| 诸城市| 通渭县| 巴里| 陆河县| 大同市| 佛教| 绥江县| 榕江县| 小金县| 郧西县| 遂昌县| 鹤岗市| 邯郸县| 会泽县| 泗水县| 白沙| 剑川县| 全南县| 通化县| 师宗县| 凤城市| 通化市| 阜康市| 平顶山市| 花莲市| 西峡县| 华池县| 五台县| 西林县| 故城县| 惠安县| 大足县| 西城区| 浏阳市| 南部县| 伊春市| 左权县|