之前,對一個列表中的字符串進行拼接時,常見的代碼如示例1所示:app
List<String> ids = ImmutableList.of("1", "2", "3"); StringBuilder sb = new StringBuilder(); for (String id : ids) { if (sb.length() > 0) { sb.append(","); } sb.append(id); } System.out.println(sb);
1,2,3
示例1的代碼沒有問題,結果也是正確的,惟一的缺憾就是:代碼比較長。學習
在JDK8以後,上述代碼能夠簡化:ui
List<String> ids = ImmutableList.of("1", "2", "3"); System.out.println(String.join(",", ids));
1,2,3
代碼由原來的9行縮短到2行,很是簡潔,最主要的是節省了時間(時間就是生命啊)。指針
JDK是如何實現的呢,源碼以下:code
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) { Objects.requireNonNull(delimiter); Objects.requireNonNull(elements); StringJoiner joiner = new StringJoiner(delimiter); for (CharSequence cs: elements) { joiner.add(cs); } return joiner.toString(); }
原來是使用了StringJoiner,StringJoiner是JDK8爲了方便構造限定分隔符,甚至於給定前綴和後綴,而提供的一個類,示例代碼以下:element
StringJoiner sj = new StringJoiner(",","{","}"); sj.add("first").add("second").add("third"); System.out.println(sj.toString());
{first,second,third}
結合JDK8的stream,能夠拼接列表元素:開發
List<Integer> numbers = ImmutableList.of(1, 2, 3, 4, 5); System.out.println(numbers.stream().map(Object::toString).collect(Collectors.joining(",")));
1,2,3,4,5
在開發的過程當中,常常遇到將字符串追加到已有的字段中,例如:將用戶的一些數據追加到一個字段中。當時看到這個需求後,憑藉第一印象,當即寫出了以下的代碼:rem
User user = new User(); StringBuilder sb = new StringBuilder(user.getRemark()); List<String> ids = ImmutableList.of("1", "2", "3"); for (String id : ids) { if (sb.length() > 0) { sb.append(","); } sb.append(id); } user.setRemark(sb.toString()); System.out.println(user);
運行,居然報空指針異常,一口老血噴了出來。經過異常信息,結合StringBuilder源碼:字符串
public StringBuilder(String str) { super(str.length() + 16); append(str); }
oh my god,在StringBuilder初始化時,爲了初始化空間的大小,取了字符串的長度。然而,新用戶的remark字段是空的,取其長度,字段就報錯了。
結合前面學習的StringJoiner,新的代碼以下:get
User user = new User(); List<String> ids = ImmutableList.of("1", "2", "3"); StringJoiner sj = new StringJoiner(","); if (StringUtils.isNoneEmpty(user.getRemark())) { sj.add(user.getRemark()); } for (String id : ids) { sj.add(id); } System.out.println(sj.toString());
1,2,3
固然,若是還想再短一點,能夠將for循環簡寫:
User user = new User(); List<String> ids = ImmutableList.of("1", "2", "3"); StringJoiner sj = new StringJoiner(","); if (StringUtils.isNoneEmpty(user.getRemark())) { sj.add(user.getRemark()); } sj.add(String.join(",", ids)); System.out.println(sj.toString());