I implemented something like PHP's implode function in Java.
(Addition) For Java8, [join](https://docs.oracle.com/javase/jp/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang. There seems to be a function called Iterable-). @nishemon Thank you for your comment!
/**
* Join list elements with a string
*
* @param stringList The list of strings to implode.
* @param glue The String for joining list.
* @return Returns a string containing a string representation of all the list elements
* in the same order, with the glue string between each element.
*/
public static String implode(List<String> stringList, String glue) {
StringBuilder stringBuilder = new StringBuilder();
int index = 0;
int size = stringList.size();
for (String value : stringList) {
stringBuilder.append(value);
if (index < size - 1) {
stringBuilder.append(glue);
}
index++;
}
return stringBuilder.toString();
}
(Addition) I was taught a general-purpose implementation. @shiracamus Thank you for your comment!
public static String implode(Iterable<? extends CharSequence> values, CharSequence glue) {
StringBuilder buffer = new StringBuilder();
CharSequence separator = "";
for (CharSequence value : values) {
buffer.append(separator).append(value);
separator = glue;
}
return buffer.toString();
}
(Addition) I was taught the implementation again. @ saka1029 Thank you for your comment!
public static <T> String implode(List<T> list, String glue) {
StringBuilder sb = new StringBuilder();
for (T e : list) {
sb.append(glue).append(e);
}
return sb.substring(glue.length());
}
Only one simple one for the time being
@Test
public void testImplode() {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
String glue = " ";
String actual = Util.implode(list, glue);
String expected = "A B C";
assertEquals(expected, actual);
}
Looking at the PHP manual, it says:
Note: implode () can accept arguments in either order for historical reasons. However, from the point of view of consistency with explode (), it would be less confusing to use the order of the arguments described in the documentation.
Also, in PHP, the default of glue
is an empty string, but this time it is not considered.
If you do, it may be good to make something overloaded like this.
public static String implode(List<String> stringList) {
return implode(stringList, "");
}
Please let me know if there is something wrong or a better way! : pray:
Recommended Posts