Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active July 5, 2016 08:37
Show Gist options
  • Save loicdescotte/b1fb18657c269f91e8ebc1b187cef0ab to your computer and use it in GitHub Desktop.
Save loicdescotte/b1fb18657c269f91e8ebc1b187cef0ab to your computer and use it in GitHub Desktop.

How to retrieve List("a", "b") from a list of optional values

A very common use case when dealing with options...

Scala

val values = List(Some("a"), None, Some("b")).flatten

Java

List<Optional<String>> optionalValues = Arrays.asList(Optional.of("a"), Optional.empty(), Optional.of("b"));
List<String> values = optionalValues.stream()
                        .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
                        .collect(Collectors.toList());

Kotlin

val values  = listOf("a", null, "b").filterNotNull()

Note : it's different to use null in Kotlin because listOf("a", null, "b")will be infered as a List<String?>, ? is the replacement for Option/Optional in Kotlin and allows to use null safely.

@emmanuelbernard
Copy link

In Ceylon

value values = ["a", null, "b"].coalesced;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment