Created
January 18, 2018 05:01
-
-
Save Allan-Gong/548fea5f9eb2e71c0470cee4be593a6e to your computer and use it in GitHub Desktop.
Options to flatMap a list of Optionals in Java8
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Ways to transform List<Optional<T>> to List<T> (excluding empty ones) | |
// 1. Using filter() | |
List<String> filteredList = listOfOptionals.stream() | |
.filter(Optional::isPresent) | |
.map(Optional::get) | |
.collect(Collectors.toList()); | |
// 2. Using flatMap() | |
List<String> filteredList = listOfOptionals.stream() | |
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty()) | |
.collect(Collectors.toList()); | |
// 3. Java 9's Opional::stream | |
List<String> filteredList = listOfOptionals.stream() | |
.flatMap(Optional::stream) | |
.collect(Collectors.toList()); | |
// 4. Create a custom collector (my favorate in Java 8 if you need to do this a lot) | |
// PresentCollector.java | |
package com.example.Collector; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Optional; | |
import java.util.stream.Collector; | |
public final class PresentCollector { | |
public static <T> Collector<Optional<T>, List<T>, List<T>> toList() { | |
return Collector.of(ArrayList::new, PresentCollector::accumulate, PresentCollector::combine); | |
} | |
private static <T> void accumulate(List<T> a, Optional<T> v) { | |
v.ifPresent(a::add); | |
} | |
private static <T> List<T> combine(List<T> x, List<T> y) { | |
x.addAll(y); | |
return x; | |
} | |
private PresentCollector() { | |
} | |
} | |
// Usage | |
List<String> filteredList = listOfOptionals.collect(PresentCollector.toList()); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment