运用 StringJoiner 高效的拼接字符串
package com. zhong. stringdemo ;
import java. util. ArrayList ;
import java. util. StringJoiner ;
public class Test {
public static void main ( String [ ] args) {
ArrayList < String > s = new ArrayList < > ( ) ;
s. add ( "11" ) ;
s. add ( "33" ) ;
s. add ( "22" ) ;
System . out. println ( arrayToString1 ( s) ) ;
System . out. println ( arrayToString2 ( s) ) ;
}
public static String arrayToString1 ( ArrayList < String > arr) {
if ( arr. isEmpty ( ) ) {
return "" ;
}
StringBuffer sb = new StringBuffer ( "[" ) ;
arr. forEach ( x -> sb. append ( x) . append ( ", " ) ) ;
sb. deleteCharAt ( sb. length ( ) - 1 ) . deleteCharAt ( sb. length ( ) - 1 ) . append ( "]" ) ;
return sb. toString ( ) ;
}
public static String arrayToString2 ( ArrayList < String > arr) {
if ( arr. isEmpty ( ) ) {
return "" ;
}
StringJoiner sj = new StringJoiner ( ", " , "[" , "]" ) ;
arr. forEach ( sj:: add ) ;
return sj. toString ( ) ;
}
}