protected static String paramsAsString(Object[] args) {
return Arrays.stream(args).map((o) -> o != null && o.getClass().isArray() ? ArrayUtils.toString(o) : o)
.collect(Collectors.toList()).toString();
}
unit test
public void paramsAsString() throws Exception {
String[] strings = {"1" , "2"};
int[] ints = {3,4};
int[] intsEmpty = {3,4};
Object[] args = {"aaa" ,"zzz" , ints , strings, intsEmpty, null};
String paramsAsString = paramsAsString(args);
assertEquals("[aaa, zzz, {3,4}, {1,2}, {3,4}, null]", paramsAsString);
}
I'm just learning stream api. I wonder is there there any way to simplify this stream expression and remove the complex if?
If you just reference ArrayUtils::toString
, you avoid the conditional:
protected static String paramsAsString(Object[] args) {
return Arrays.stream(args)
.map(ArrayUtils::toString)
.collect(Collectors.toList()).toString();
}
but your test fails beause you get:
[aaa, zzz, {3,4}, {1,2}, {3,4}, {}]
instead of
[aaa, zzz, {3,4}, {1,2}, {3,4}, null]
You could "hack" this with a regex:
return Arrays.stream(args)
.map(ArrayUtils::toString)
.collect(Collectors.toList())
.toString().replaceAll("\\{\\}" , "null");
}
But personally, i would keep the conditional and convert the lambda to another utility method:
public class MyArrayUtils {
protected static String paramsAsString(Object[] args) {
return Arrays.stream(args)
.map(MyArrayUtils::objectToString)
.collect(Collectors.toList()).toString();
}
private static String objectToString(Object object) {
return object == null ? null : ArrayUtils.toString(object);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With