简体   繁体   中英

Generic Function to Print a List of Objects

When printing a list I do not like the layout: it is printed as one long line. I would prefer a line pro element.

I created a version to do just that, but was wondering if it could be done better.

private static void printObjectList(List<?> objects) {
    System.out.println("[");
    objects.forEach(o -> System.out.println("    " + o));
    System.out.println("]");
}

---- Edit
With the very good tip of Erin I changed the method to:

private static void printObjectList(List<?> objects) {
    System.out.println(objects.stream()
           .map(o -> "    " + o)
           .collect(Collectors.joining("    \n", "[\n", "\n]")));
}

I only do not understand the parameters. I would expect:

           .collect(Collectors.joining("\n    ", "[", "\n]")));

---- Edit
It is not completely correct yet, because:

printObjectList(new ArrayList<Integer>());

gives:

[

]

instead of:

[
]

---- Edit
It can be solved with:

private static void printObjectList(List<?> objects) {
    if (objects.isEmpty()) {
        System.out.println("[\n]");
    } else {
        System.out.println(objects.stream()
                           .map(o -> "    " + o)
                           .collect(Collectors.joining("\n", "[\n", "\n]")));
    }
}

---- Edit
Should have thought a little longer. :'-( I really did not like the if. By rewriting the map and emptying the delimiter the conditional is not necessary any-more:

private static void printObjectList(List<?> objects) {
    System.out.println(objects.stream()
                       .map(o -> "    " + o + "\n")
                       .collect(Collectors.joining("", "[\n", "]")));
}

Instead of writing your own method, you can use Java 8 features.

For example:

System.out.println(objects.stream().map(o -> "    " + o).collect(Collectors.joining ("   \n","[\n","\n]\n")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM