轉自 http://my.oschina.net/zenglingfan/blog/134872html
寫代碼的時候,常常會碰到須要把一個List中的每一個元素,按逗號分隔轉成字符串的需求,之前是本身寫一段比較難看的代碼,先把字符串拼出來,再把最後面多餘的逗號去掉;雖然功能能夠實現,但總以爲最後加的那一步操做很沒有必要:java
public static String join(List<String> list, String seperator){ if(list.isEmpty()){ return ""; } StringBuffer sb = new StringBuffer(); for(int i=0; i<list.size(); i++){ sb.append(list.get(i)).append(seperator); } return sb.substring(0, sb.length() - seperator.length()); }
轉到java後,一直不知道有org.apache.commons.lang 這麼一個包,裏面提供了功能強大的join函數,直到有一次看到同事在用……apache
看了一下源代碼,實現的思路比較精巧,巧妙避免了像我在上面,老是須要最後再取一次substring的問題,org.apache.commons.lang.StringUtils 中 join函數代碼以下:api
/** * <p>Joins the elements of the provided array into a single String * containing the provided list of elements.</p> * * <p>No delimiter is added before or after the list. * Null objects or empty strings within the array are represented by * empty strings.</p> * * <pre> * StringUtils.join(null, *) = null * StringUtils.join([], *) = "" * StringUtils.join([null], *) = "" * StringUtils.join(["a", "b", "c"], ';') = "a;b;c" * StringUtils.join(["a", "b", "c"], null) = "abc" * StringUtils.join([null, "", "a"], ';') = ";;a" * </pre> * * @param array the array of values to join together, may be null * @param separator the separator character to use * @param startIndex the first index to start joining from. It is * an error to pass in an end index past the end of the array * @param endIndex the index to stop joining from (exclusive). It is * an error to pass in an end index past the end of the array * @return the joined String, {@code null} if null array input * @since 2.0 */ public static String join(Object[] array, char separator, int startIndex, int endIndex) { if (array == null) { return null; } int noOfItems = endIndex - startIndex; if (noOfItems <= 0) { return EMPTY; } StringBuilder buf = new StringBuilder(noOfItems * 16); for (int i = startIndex; i < endIndex; i++) { if (i > startIndex) { buf.append(separator); } if (array[i] != null) { buf.append(array[i]); } } return buf.toString(); }
以上代碼精髓在於這一句app
if (i > startIndex) { buf.append(separator); }
保證了第一次不會插入 separator,然後面插入的 separator 又都是在 array 的 value 以前,這樣最後就不會多出一個 separator.ide
本身的代碼主要是沒想到 StringBuilder 直接用 toString 獲得結果,因此之前老是不能直接在 for 循環裏作完,出來還要作一次(還要計算各類length),使得代碼很難看。函數