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();
}
单元测试
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);
}
我只是在学习流 api。 请问有什么方法可以简化这个流表达式,去掉复杂的if吗?
最佳答案
如果你只是引用 ArrayUtils::toString
,你就避免了条件:
protected static String paramsAsString(Object[] args) {
return Arrays.stream(args)
.map(ArrayUtils::toString)
.collect(Collectors.toList()).toString();
}
但是你的测试失败了,因为你得到:
[aaa, zzz, {3,4}, {1,2}, {3,4}, {}]
代替
[aaa, zzz, {3,4}, {1,2}, {3,4}, null]
你可以用正则表达式“破解”它:
return Arrays.stream(args)
.map(ArrayUtils::toString)
.collect(Collectors.toList())
.toString().replaceAll("\\{\\}" , "null");
}
但就个人而言,我会保留条件并将 lambda 转换为另一种实用方法:
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);
}
}
关于java - 有什么办法可以简化这个流表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26054363/