自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

放棄 StringBuilder!用Java8的StringJoiner

開發(fā) 后端
在閱讀項(xiàng)目代碼時(shí),突然看到了StringJoiner這個(gè)類的使用,感覺很有意思。對(duì)實(shí)際開發(fā)中也有用,原理上是運(yùn)用了StringBuilder的一個(gè)拼接字符串的封裝處理。

[[417416]]

 在閱讀項(xiàng)目代碼時(shí),突然看到了StringJoiner這個(gè)類的使用,感覺很有意思。

對(duì)實(shí)際開發(fā)中也有用,原理上是運(yùn)用了StringBuilder的一個(gè)拼接字符串的封裝處理。

為什么會(huì)新增這樣一個(gè)string輔助類?

原有的stringbuilder太死板,不支持分割,如果想讓最終的字符串以逗號(hào)隔開,需要這樣寫 

  1. StringBuilder sb = new StringBuilder();  
  2. IntStream.range(1,10).forEach(i-> 
  3.     sb.append(i+"");  
  4.     if( i < 10){  
  5.         sb.append(",")  
  6.     }  
  7. }); 

是不是太死板了,不好用,StringJoiner怎樣寫呢? 

  1. StringJoiner sj = new StringJoiner(",");  
  2. IntStream.range(1,10).forEach(i->sj.add(i+"")); 

有哪些平時(shí)用的還比較少的功能:

  •  setEmptyValue, 默認(rèn)情況下的emptyValue是前綴加后綴, 用戶可自定義emptyValue
  •  merge(StringJoiner other),合并另外一個(gè)joiner
  •  length, 當(dāng)前長度,為空看emptyValue的長度

讓我實(shí)現(xiàn)StringJoiner,我會(huì)怎么辦呢?

  •  維護(hù)一個(gè)List,最后toString的時(shí)候join一下就好了。優(yōu)勢(shì):實(shí)現(xiàn)非常方便 缺點(diǎn):list太浪費(fèi)空間(擴(kuò)容時(shí)都是按照系數(shù)擴(kuò)容的)
  •  在StringBuilder基礎(chǔ)上改造(jdk實(shí)現(xiàn)方式就是以組合的形式增強(qiáng)的StringBuilder

jdk實(shí)現(xiàn)的源碼分析

  •  成員變量 
  1. private final String prefix;  
  2.     private final String delimiter;  
  3.     private final String suffix;  
  4.     /*  
  5.      * StringBuilder value -- at any time, the characters constructed from the  
  6.      * prefix, the added element separated by the delimiter, but without the  
  7.      * suffix, so that we can more easily add elements without having to jigger  
  8.      * the suffix each time.  
  9.      */  
  10.     private StringBuilder value;  
  11.     /*  
  12.      * By default, the string consisting of prefix+suffix, returned by  
  13.      * toString(), or properties of value, when no elements have yet been added,  
  14.      * i.e. when it is empty.  This may be overridden by the user to be some  
  15.      * other value including the empty String.  
  16.      */  
  17.     private String emptyValue; 

其實(shí)從成員變量的注釋里就能看出他們的作用和需要注意的點(diǎn)了

  •  構(gòu)造函數(shù) 
  1. public StringJoiner(CharSequence delimiter,  
  2.                         CharSequence prefix,  
  3.                         CharSequence suffix) {  
  4.         Objects.requireNonNull(prefix, "The prefix must not be null");  
  5.         Objects.requireNonNull(delimiter, "The delimiter must not be null");  
  6.         Objects.requireNonNull(suffix, "The suffix must not be null");  
  7.         // make defensive copies of arguments  
  8.         this.prefix = prefix.toString();  
  9.         this.delimiter = delimiter.toString();  
  10.         this.suffix = suffix.toString();  
  11.         // ?。?!構(gòu)造時(shí)就直接將emptyValue拼接好了。  
  12.         thisthis.emptyValue = this.prefix + this.suffix;  
  13.     } 

為什么要一開始就構(gòu)造好呢?如果我想直接自定義emptyValue直接用構(gòu)造函數(shù)初始化不是更方便嗎?是因?yàn)榻^大多數(shù)場(chǎng)景下都不會(huì)自定義emptyValue的場(chǎng)景嗎?不對(duì)啊,感覺這個(gè)場(chǎng)景非常必要啊。。。

  •  添加元素 
  1. public StringJoiner add(CharSequence newElement) {  
  2.         prepareBuilder().append(newElement);  
  3.         return this;  
  4.  
  5. private StringBuilder prepareBuilder() {  
  6.         // 從構(gòu)造函數(shù)和類變量的聲明可以看出,沒有添加元素前stringbuilder是沒有初始化的  
  7.         if (value != null) {  
  8.             // 已經(jīng)有元素存在的情況下,添加元素前先將分隔符添加進(jìn)去  
  9.             value.append(delimiter);  
  10.         } else {  
  11.             // 沒有元素存在的情況下先把前綴加進(jìn)去  
  12.             value = new StringBuilder().append(prefix);  
  13.         }  
  14.         return value;  

可以看出再添加元素的過程中就已經(jīng)把前綴和分割字符什么的都處理好了,全部都在stringbuilde中了,唯一沒有處理的就是后綴。 為什么?這樣做tostring什么的時(shí)候真的超級(jí)方便的有木有。。。。。

  • 關(guān)鍵的toString 
  1. public String toString() {  
  2.     if (value == null) {  
  3.         // 這里如果沒有自定義空值就是前綴+后綴咯。。 
  4.         return emptyValue;  
  5.     } else {  
  6.         // 為什么不直接value.toString()+suffix?????  
  7.         if (suffix.equals("")) {  
  8.             return value.toString();  
  9.         } else {  
  10.             int initialLength = value.length();  
  11.             String result = value.append(suffix).toString();  
  12.             // reset value to pre-append initialLength  
  13.             value.setLength(initialLength);  
  14.             return result;  
  15.         }  
  16.     }  

為什么不直接value.toString()+suffix?答案在merge方法

  •  merge 
  1. public StringJoiner merge(StringJoiner other) {  
  2.         Objects.requireNonNull(other);  
  3.         if (other.value != null) {  
  4.             final int length = other.value.length();  
  5.             // 下面這段注釋是說避免merge(this)時(shí)受影響,為什么?  
  6.             // lock the length so that we can seize the data to be appended  
  7.             // before initiate copying to avoid interference, especially when  
  8.             // merge 'this'  
  9.             StringBuilder builder = prepareBuilder();  
  10.             builder.append(other.value, other.prefix.length(), length);  
  11.         }  
  12.         return this;  
  13.     }  
  14. private StringBuilder prepareBuilder() {  
  15.         if (value != null) {  
  16.             value.append(delimiter);  
  17.         } else {  
  18.             value = new StringBuilder().append(prefix);  
  19.         }  
  20.         return value;  
  21.     } 

merge的思路是用當(dāng)前的striingBuilder去append other的value(必須去掉前綴),源碼注釋中的merge 'this'問題是什么呢?prepareBuilder()的時(shí)候可能會(huì)先append(delimiter),如果other就是this,那么length其實(shí)就多了一個(gè)delimiter,此時(shí)append還是得以添加前的length為準(zhǔn)。

merge的實(shí)現(xiàn)方式?jīng)Q定了toString時(shí)不能直接value.append(suffix).toString(),因?yàn)?builder.append(other.value, other.prefix.length(), length);這行代碼,默認(rèn)加上suffix后這里的merge的length得減去suffix的length(嗯,看來作者是想得多好多),而且merge時(shí)得把另外一個(gè)sj的內(nèi)容append到當(dāng)前這個(gè)sj的suffix之前(想想就麻煩多了~)

  •  length 
  1. public int length() {  
  2.         // Remember that we never actually append the suffix unless we return  
  3.         // the full (present) value or some sub-string or length of it, so that  
  4.         // we can add on more if we need to.  
  5.         return (value != null ? value.length() + suffix.length() :  
  6.             emptyValue.length());  
  7.     } 

沒什么好說的,記住length不只是add的元素的length,還有前后綴。

總結(jié)

  •  基于StringBuilder實(shí)現(xiàn),add時(shí)就把prefix和分隔符給加上了,suffix永遠(yuǎn)都不加,知道toString和length調(diào)用時(shí)才加入計(jì)算。這樣帶來的merge操作實(shí)現(xiàn)的極大便利性!?。。。W(xué)到了,真的不錯(cuò)
  •  emptyValue這個(gè)一定要構(gòu)造時(shí)就生成嗎?用戶想有自己的默認(rèn)值還需要先構(gòu)造實(shí)例再注入嗎。。。。這個(gè)覺得還是有點(diǎn)奇怪
  •  Objects這個(gè)工具方法是返回的校驗(yàn)的值本身,不錯(cuò)。 
  1. public StringJoiner setEmptyValue(CharSequence emptyValue) {  
  2. // 注意這個(gè)Objects.requireNonNull方法是return的第一個(gè)參數(shù)。。。  
  3.         this.emptyValue = Objects.requireNonNull(emptyValue,  
  4.             "The empty value must not be null").toString();  
  5.         return this;  
  6.  

 

責(zé)任編輯:龐桂玉 來源: Java編程
相關(guān)推薦

2021-04-21 10:36:47

StringBuildJava8StringJoine

2024-03-18 00:00:00

CalendaJava8Date

2019-02-27 09:08:20

Java 8StringJoineIDEA

2020-07-24 08:11:04

Java8ava5語言

2023-07-26 07:13:55

函數(shù)接口Java 8

2017-10-31 20:45:07

JavaJava8Optional

2023-03-15 17:37:26

Java8ListMap

2020-11-19 07:51:06

StringJoine分隔符使用

2020-05-25 16:25:17

Java8Stream函數(shù)式接口

2021-02-24 10:03:17

Java8日期API

2023-05-12 07:40:01

Java8API工具

2012-10-16 09:25:33

Windows 8

2014-12-22 10:14:31

Java8

2020-05-29 07:20:00

Java8異步編程源碼解讀

2012-07-18 09:45:32

Java 8ScalaLambda

2009-06-30 15:18:10

StringBuildJava

2011-10-17 10:02:00

Windows 8

2016-12-27 09:46:55

Java 8StringBuild

2023-12-21 08:02:21

CPUJava8列表

2013-08-06 13:58:27

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)