参考文章

StringJoiner

作用

StringJoiner是Java8新出的一个类,用于构造由分隔符分隔的字符序列,并可选择性地从提供的前缀开始和以提供的后缀结尾。省的我们开发人员再次通过StringBuffer或者StingBuilder拼接。

源码

package java.util;/*** {@code StringJoiner} is used to construct a sequence of characters separated* by a delimiter and optionally starting with a supplied prefix* and ending with a supplied suffix.* <p>* Prior to adding something to the {@code StringJoiner}, its* {@code sj.toString()} method will, by default, return {@code prefix + suffix}.* However, if the {@code setEmptyValue} method is called, the {@code emptyValue}* supplied will be returned instead. This can be used, for example, when* creating a string using set notation to indicate an empty set, i.e.* <code>"{}"</code>, where the {@code prefix} is <code>"{"</code>, the* {@code suffix} is <code>"}"</code> and nothing has been added to the* {@code StringJoiner}.** @apiNote* <p>The String {@code "[George:Sally:Fred]"} may be constructed as follows:** <pre> {@code* StringJoiner sj = new StringJoiner(":", "[", "]");* sj.add("George").add("Sally").add("Fred");* String desiredString = sj.toString();* }</pre>* <p>* A {@code StringJoiner} may be employed to create formatted output from a* {@link java.util.stream.Stream} using* {@link java.util.stream.Collectors#joining(CharSequence)}. For example:** <pre> {@code* List<Integer> numbers = Arrays.asList(1, 2, 3, 4);* String commaSeparatedNumbers = numbers.stream()*     .map(i -> i.toString())*     .collect(Collectors.joining(", "));* }</pre>** @see java.util.stream.Collectors#joining(CharSequence)* @see java.util.stream.Collectors#joining(CharSequence, CharSequence, CharSequence)* @since  1.8
*/
public final class StringJoiner {private final String prefix;           // 前缀private final String delimiter;    // 间隔符private final String suffix;      // 后缀/** StringBuilder value -- at any time, the characters constructed from the* prefix, the added element separated by the delimiter, but without the* suffix, so that we can more easily add elements without having to jigger* the suffix each time.*/private StringBuilder value;          // 值/** By default, the string consisting of prefix+suffix, returned by* toString(), or properties of value, when no elements have yet been added,* i.e. when it is empty.  This may be overridden by the user to be some* other value including the empty String.*/private String emptyValue;         // 空值/*** 重载调用* 默认前缀和后缀为 ""*/public StringJoiner(CharSequence delimiter) {this(delimiter, "", "");}/*** 若其中有null 则抛出异常*/public StringJoiner(CharSequence delimiter,CharSequence prefix,CharSequence suffix) {Objects.requireNonNull(prefix, "The prefix must not be null");Objects.requireNonNull(delimiter, "The delimiter must not be null");Objects.requireNonNull(suffix, "The suffix must not be null");// make defensive copies of argumentsthis.prefix = prefix.toString();this.delimiter = delimiter.toString();this.suffix = suffix.toString();this.emptyValue = this.prefix + this.suffix;}/*** 设置空值,检查是否为null*/public StringJoiner setEmptyValue(CharSequence emptyValue) {this.emptyValue = Objects.requireNonNull(emptyValue,"The empty value must not be null").toString();return this;}/*** 重写的toString()*/@Overridepublic String toString() {if (value == null) {return emptyValue;} else {if (suffix.equals("")) {return value.toString();} else {int initialLength = value.length();String result = value.append(suffix).toString();// reset value to pre-append initialLengthvalue.setLength(initialLength);return result;}}}/*** Adds a copy of the given {@code CharSequence} value as the next* element of the {@code StringJoiner} value. If {@code newElement} is* {@code null}, then {@code "null"} is added.** @param  newElement The element to add* @return a reference to this {@code StringJoiner}*/public StringJoiner add(CharSequence newElement) {prepareBuilder().append(newElement);return this;}/*** 合并StringJoiner* 将后面的数据添加进前一个*/public StringJoiner merge(StringJoiner other) {Objects.requireNonNull(other);if (other.value != null) {final int length = other.value.length();// lock the length so that we can seize the data to be appended// before initiate copying to avoid interference, especially when// merge 'this'StringBuilder builder = prepareBuilder();builder.append(other.value, other.prefix.length(), length);}return this;}/*** 初始化* 先添加前缀,若有数据,则每次先添加间隔符*/private StringBuilder prepareBuilder() {if (value != null) {value.append(delimiter);} else {value = new StringBuilder().append(prefix);}return value;}/*** Returns the length of the {@code String} representation* of this {@code StringJoiner}. Note that if* no add methods have been called, then the length of the {@code String}* representation (either {@code prefix + suffix} or {@code emptyValue})* will be returned. The value should be equivalent to* {@code toString().length()}.** @return the length of the current value of {@code StringJoiner}*/public int length() {// Remember that we never actually append the suffix unless we return// the full (present) value or some sub-string or length of it, so that// we can add on more if we need to.return (value != null ? value.length() + suffix.length() :emptyValue.length());}
}

测试代码

StringJoiner joiner = new StringJoiner(":","{","}");
joiner.add("1");
joiner.add("2");
joiner.add("3");
joiner.add("4");
System.out.println(joiner);

输出 {1:2:3:4}

StringJoiner相关推荐

  1. 字符串拼接还在用StringBuilder?快试试Java8中的StringJoiner吧,真香!

    点击关注公众号,Java干货及时送达 前言 之前,我们经常会通过StringBuffer或者StingBuilder对字符串进行拼接,但是你知道Java8中推出的StringJoiner吗?它比前者更 ...

  2. java string set_Java StringJoiner setEmptyValue()用法及代码示例

    StringJoiner的setEmptyValue(CharSequence emptyValue)设置确定此StringJoiner的字符串表示形式且尚未添加任何元素(即当它为空时)时要使用的字符 ...

  3. java_options字符串拼接_java8 StringJoiner拼接字符串

    StringJoiner可以用来拼接字符串. 字符串拼接 示例如下: public static void test1() { StringJoiner stringJoiner = new Stri ...

  4. Java8 拼接字符串 StringJoiner

    StringJoiner是Java8新出的一个类,用于构造由分隔符分隔的字符序列,并可选择性地从提供的前缀开始和以提供的后缀结尾.省的我们开发人员再次通过StringBuffer或者StingBuil ...

  5. Java 8中的StringJoiner与String.join的示例

    将多个String文字或对象合并为一个是常见的编程要求,并且经常会发现需要为应用程序将String列表或String集合转换为CSV String的情况. 长期以来,JDK API无法将多个Strin ...

  6. Java 8 StringJoiner

    在Java 8发行版中,最受关注的是Lamda,新的Date API和Nashorn Javascript引擎. 在这些阴影下,有较小但有趣的变化. 其中之一是StringJoiner的引入. Str ...

  7. java 循环拼接字符串用分号隔开_Java 8中字符串拼接新姿势:StringJoiner

    在为什么阿里巴巴不建议在for循环中使用"+"进行字符串拼接一文中,我们介绍了几种Java中字符串拼接的方式,以及优缺点.其中还有一个重要的拼接方式我没有介绍,那就是Java 8中 ...

  8. c++ 字符串拼接_字符串拼接新姿势:StringJoiner

    来自:Hollis(微信号:hollischuang) 在为什么阿里巴巴不建议在for循环中使用"+"进行字符串拼接一文中,我们介绍了几种Java中字符串拼接的方式,以及优缺点.其 ...

  9. [转载] Java StringBuilder StringJoiner

    参考链接: 何时在StringBuilder上使用StringJoiner 1. StringBuilder Java编译器对String做了特殊处理,使得我们可以直接用+拼接字符串. 虽然可以直接拼 ...

  10. java库里_java8之StringJoiner。终于有像guava类库里的功能了

    StringJoiner底层也是咱们平时用StringBuilder容器.只不过容量没提供设置初始容量,默认16 characters. 不说了.代码: package com.doctor.java ...

最新文章

  1. mysql5.1 与mysql5.5 字符集设置区别
  2. 设计模式之美:Type Object(类型对象)
  3. React系列---React+Redux工程目录结构划分
  4. 初识ABP vNext(4):vue用户登录菜单权限
  5. psycopg2.errors.UndefinedTable: relation “xxxx“ does not exist
  6. 湖南工大11级C语言网上作业,湖南工大11级C语言网上作业之《最简单的程序设计》.docx...
  7. 牛客多校第二场 G transform
  8. android 搭建短信平台,Android 短信SDK集成文档 | Mob文档中心
  9. java音频文件怎么打开_java 怎么读取音乐文件
  10. access函数使用方法
  11. 阿里开发规约之编程规约(4)
  12. ttl低电平接大电阻_电压不稳定?那是你不懂上拉/下拉电阻原理,5分钟教你应用!...
  13. 焊接机器人编程c语言,机器人现场编程与调试(cnc上下料,弧焊,喷涂,点焊等),就是这么全!...
  14. Eclipse护眼背景色
  15. 日有所思(6)——直流电机注意点
  16. 【搬运】黑苹果台式机机型选择指导 By 黑果小兵
  17. python中while循环并列_Python中while循环的一个问题
  18. 手把手教你在GitHub上传项目(超详细)
  19. 【STM32F429开发板用户手册】第7章 STM32F429下载和调试方法(IAR8)
  20. 印度理工学院有多难考?

热门文章

  1. C#:System.Data.SQLite数据库介绍
  2. 11位大牛与您共建数智升级路径
  3. 车站计算机系统需要具备几天数据储存能力,(复习资料)城市轨道交通车站设备1.doc...
  4. 【图像聚类】基于matlab GUI K-means算法图像聚类【含Matlab源码 1787期】
  5. 【风速预测】基于matlab EMD+模拟退火算法优化DBN风速预测【含Matlab源码 JQ003期】
  6. 【心电信号】基于matlab自适应滤波算法胎儿心电信号提取【含Matlab源码 953期】
  7. 【优化预测】基于matlab飞蛾扑火算法优化LSSVM预测【含Matlab源码 110期】
  8. SPSS遇到缺失值怎么办?删除还是替换?【SPSS 067期】
  9. 【TWVRP】基于matlab蚁群算法求解带时间窗的多中心车辆路径规划问题【含Matlab源码 112期】
  10. ai人工智能的本质和未来_人工智能简介:这就是未来