Created
May 3, 2013 11:04
-
-
Save mdread/5508519 to your computer and use it in GitHub Desktop.
method "mkString"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String mkString(Iterable<?> values, String start, String sep, String end){ | |
// if the array is null or empty return an empty string | |
if(values == null || !values.iterator().hasNext()) | |
return ""; | |
// move all non-empty values from the original array to a new list (empty is a null, empty or all-whitespace string) | |
List<String> nonEmptyVals = new LinkedList<String>(); | |
for (Object val : values) { | |
if(val != null && val.toString().trim().length() > 0){ | |
nonEmptyVals.add(val.toString()); | |
} | |
} | |
// if there are no "non-empty" values return an empty string | |
if(nonEmptyVals.size() == 0) | |
return ""; | |
// iterate the non-empty values and concatenate them with the separator, the entire string is surrounded with "start" and "end" parameters | |
StringBuilder result = new StringBuilder(); | |
result.append(start); | |
int i = 0; | |
for (String val : nonEmptyVals) { | |
if(i > 0) | |
result.append(sep); | |
result.append(val); | |
i++; | |
} | |
result.append(end); | |
return result.toString(); | |
} | |
public static String mkString(Iterable<?> values, String sep){ | |
return mkString(values, "", sep, ""); | |
} | |
public static String mkString(Iterable<?> values){ | |
return mkString(values, "", "", ""); | |
} | |
// same methods with array parameter | |
public static String mkString(Object[] values, String start, String sep, String end){ | |
return mkString(Arrays.asList(values), start, sep, end); | |
} | |
public static String mkString(Object[] values, String sep){ | |
return mkString(Arrays.asList(values), sep); | |
} | |
public static String mkString(Object[] values){ | |
return mkString(Arrays.asList(values)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment