Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to simplify this stream expression?

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?

like image 353
Pan Bydlak Avatar asked Jan 10 '23 17:01

Pan Bydlak


1 Answers

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);
     }
}
like image 168
gontard Avatar answered Jan 21 '23 19:01

gontard