Write a method, that takes an array of any type and a delimeter, return the string representation of array elements.
Signature
String toString(Object[] array, String delimiter)
Find the below working application.
ArrayAsString.java
package com.sample.app.arrays;
import java.util.StringJoiner;
public class ArrayAsString {
public static String toString(final Object[] array, final String delimeter) {
if (array == null || array.length == 0) {
return "";
}
String delimeterToApply = delimeter;
if (delimeter == null || delimeter.isEmpty()) {
delimeterToApply = ",";
}
final StringJoiner stringJointer = new StringJoiner(delimeterToApply);
for (Object obj : array) {
if (obj == null) {
stringJointer.add("null");
} else {
stringJointer.add(obj.toString());
}
}
return stringJointer.toString();
}
public static void main(String[] args) {
System.out.println(toString(new Integer[] {}, null));
System.out.println(toString(new Integer[] { 2, 3, 5 }, "-->"));
System.out.println(toString(new Integer[] { 2, null, 3, null, 5 }, "-->"));
}
}
Output
2-->3-->5 2-->null-->3-->null-->5
You may like
Generic method to concatenate two arrays in Java
Quick guide to assertions in Java
No comments:
Post a Comment