Java實用工具之StringJoiner詳解
背景
在平時的業務開發中,我們可能會遇到字符串列表根據分隔符進行拼接的需求。比如:
輸入:
數組:[“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; }
到此這篇關於Java實用工具之StringJoiner詳解的文章就介紹到這瞭,更多相關Java StringJoiner內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- Java8優雅的字符串拼接工具類StringJoiner實例代碼
- Java基礎入門語法–String類
- 詳解Java中String類的各種用法
- Java有哪些操作字符串的類?區別在哪?
- java實戰小技巧之優雅的實現字符串拼接