Skip to content

Instantly share code, notes, and snippets.

@loicdescotte
Last active July 5, 2016 08:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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.

@KessirCTED
Copy link

Java, as verbose as ever.

@emmanuelbernard
Copy link

emmanuelbernard commented Jul 5, 2016

I suppose in idiomatic Java, you probably would rather write

List<String> optionalValues = Arrays.asList("a", null, "b");
List<String> values = optionalValues.stream()
                        .filter(o -> o != null)  // or .filter(Objects::nonNull)
                        .collect(Collectors.toList());

Which is verbose but relatively clear with the intent. Optional in Java has a more restricted use than the Option in Scala or other recent languages.

@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