Join an array of Strings together.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
class Main {
/**
* Join an array of Strings together.
*
* @param glue Token to place between Strings.
* @param pieces Array of Strings to join.
* @return String presentation of joined Strings.
* @see #join(String,java.util.Iterator)
*/
public static String join(List<String> pieces, String glue) {
return join(pieces.iterator(), glue);
}
/**
* Join an Iteration of Strings together.
* <p/>
* <h5>Example</h5>
* <p/>
* <p/>
*
* <pre>
* // get Iterator of Strings ("abc","def","123");
* Iterator i = getIterator();
* out.print(TextUtils.join(", ", i));
* // prints: "abc, def, 123"
* </pre>
*
* @param glue Token to place between Strings.
* @param pieces Iteration of Strings to join.
* @return String presentation of joined Strings.
*/
private static String join(Iterator<String> pieces, String glue) {
StringBuilder s = new StringBuilder();
while (pieces.hasNext()) {
s.append(pieces.next());
if (pieces.hasNext()) {
s.append(glue);
}
}
return s.toString();
}
/**
* Join an array of Strings together.
*
* @param glue Token to place between Strings.
* @param pieces Array of Strings to join.
* @return String presentation of joined Strings.
* @see #join(String,java.util.Iterator)
*/
public static String join(Map<String, String> pieces, String glue) {
List<String> tmp = new ArrayList<String>(pieces.size());
for (Map.Entry<String, String> entry : pieces.entrySet()) {
tmp.add(entry.getKey() + ":" + entry.getValue());
}
return join(tmp, glue);
}
}
Related examples in the same category