Java StringJoiner Java实用工具之StringJoiner详解
黄智霖-blog 人气:0想了解Java实用工具之StringJoiner详解的相关内容吗,黄智霖-blog在本文为您仔细讲解Java StringJoiner的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,StringJoiner,Java实用工具,下面大家一起来学习吧。
背景
在平时的业务开发中,我们可能会遇到字符串列表根据分隔符进行拼接的需求。比如:
输入:
数组:[“a”,“b”,“c”]分隔符:","输出:
“a,b,c”
处理
通常我们可以使用StringBuilder根据下标位置决定是否需要添加分隔符以达到目的,比如:
public static void main(String[] args) { StringBuilder sb = new StringBuilder(); String[] strings = new String[]{"a", "b", "c"}; String delimiter = ","; for (int i = 0; i < strings.length; i++) { if (i != 0) { sb.append(delimiter); } sb.append(strings[i]); } System.out.println(sb.toString()); }
或者:
public static void main(String[] args) { StringBuilder sb = new StringBuilder(); String[] strings = new String[]{"a", "b", "c"}; String delimiter = ","; int tmp = strings.length - 1; for (int i = 0; i < strings.length; i++) { sb.append(strings[i]); if (i != tmp) { sb.append(delimiter); } } System.out.println(sb.toString()); }
但是每次遇到这种情况都去这样拼接很麻烦,而且如果使用迭代器,没有下标就不能使用这种方法。那么就每次append分隔符,最后再截断:
public static void main(String[] args) { StringBuilder sb = new StringBuilder(); String[] strings = new String[]{"a", "b", "c"}; String delimiter = ","; for (String str:strings) { sb.append(str).append(delimiter); } System.out.println(sb.substring(0,sb.length()-1)); }
所以通常情况下,我们都会去扩展一个StringBuilder以提供分隔符组装的功能,博主平时是这样弄的:
public class MyStringBuilder { private StringBuilder stringBuilder; private String delimiter; public MyStringBuilder(String delimiter) { this.delimiter = delimiter; } public MyStringBuilder append(String item) { getStringBuilder().append(item); return this; } /** * 模拟的就是这个逻辑: * if(index != 0){ * append(delimiter); * } * append(str); * * @return */ private StringBuilder getStringBuilder() { if (stringBuilder == null) { //相当于index==0, stringBuilder = new StringBuilder(); } else { stringBuilder.append(delimiter); } return stringBuilder; } @Override public String toString() { return stringBuilder == null ? "" : stringBuilder.toString(); } }
在初始化的时候指定分隔符,然后每次直接append就行了,由内部决定在何时添加分隔符。
在JDK1.8之后,提供了一个StringJoiner类,提供了类似的功能,可以在初始化的时候指定分隔符和前缀后缀:
StringJoiner sj = new StringJoiner(",","(",")"); sj.add("a").add("b").add("c"); System.out.println(sj.toString()); //输出:(a,b,c)
博主大致看了一下StringJoiner的实现逻辑,很简单,和咱们扩展StringBuilder基本是一样的逻辑,另外加入了前缀后缀,然后多了一个merge的功能:
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; } ———————————————— 版权声明:本文为CSDN博主「黄智霖-blog」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/huangzhilin2015/article/details/115376792
加载全部内容