How to toString() a List like this one : List<Option>?

1.9k views Asked by At

Suppose I have a list of an object called Option :

List<Option> opts = ArrayList<Option>();

I have override toString() for the object Option.

when I do opts.toString() that means I do toString for a List , I get some unnecessary commas ,,,,,.

I would like to change that. Please, is there a way better then for-looping inside the List to toString each element ? Hope I am clear.

3

There are 3 answers

11
Jordi Castilla On BEST ANSWER

I guess not a good idea to override toString of ArrayList, but you can create your own print function in some Utility class of your application:

public static String myToString(List<?> list) {
    StringBuilder stringList = new StringBuilder();
    String delimiter = " ";
    for (int c = 0; c < list.size(); c++) {
        stringList.append(delimiter);
        stringList.append(list.get(c));
    }
    return stringList.toString();
}
2
Rahel Lüthy On

If you were using Java 8 Optional, it would look like this:

List<Optional<String>> opts = Arrays.asList(
   Optional.of("bli"),
   Optional.<String>empty(),
   Optional.of("bla"));

String result = opts.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.joining(", "));

resulting in "bli, bla" without any extra commas.

If you can't use the official Optional class, you could maybe change your Option to behave similarly?

BTW: With Java 9 you could even replace the awkward filter(Optional::isPresent).map(Optional::get) with flatMap(Optional::stream).

0
Holger On

If you want the string representations to be glued together you may use

opts.stream().map(Object::toString).collect(Collectors.joining()));

but if you just want get rid of the comma, i.e. keep a space as separator, you can customize it as

opts.stream().map(Object::toString).collect(Collectors.joining(" ")));

or, if obsolete separators are you concern, i.e. you don’t want separators between empty strings, use

opts.stream().map(Object::toString)
    .filter(s->!s.isEmpty()).collect(Collectors.joining(" "))

If you miss the brackets, use either

opts.stream().map(Object::toString).collect(Collectors.joining(" ", "[", "]"))

or

opts.stream().map(Object::toString)
    .filter(s->!s.isEmpty()).collect(Collectors.joining(" ", "[", "]"))