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

Suppose I have an listobject with the name Option:

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

I redefine toString()for the object Option.

when I do opts.toString(), it means that I am doing toString for List, I get unnecessary commas ,,, .

I would like to change that. Please, is there a better way than for looping each item in the List toString? I hope I get it.

+4
source share
3 answers

I do not think to override toStringfrom 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();
}
+1
source

, ,

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

, .. ,

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

, , .. ,

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

,

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

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

If you used 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(", "));

leads to "bli, bla" without any additional commas.

If you cannot use the official class Optional, can you change yours Optionto behave the same way?

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

+2
source

All Articles