Skip to content

Instantly share code, notes, and snippets.

@mdread
Created July 23, 2012 16:53
Show Gist options
  • Save mdread/3164690 to your computer and use it in GitHub Desktop.
Save mdread/3164690 to your computer and use it in GitHub Desktop.
make a string from an iterator or array using an optional separator and prefix-suffix values
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(Object[] values, String start, String sep, String end){
return mkString(Arrays.asList(values), start, sep, end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment