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).
source
share