Created
July 14, 2017 09:18
-
-
Save ygrenzinger/f88e160ab7d70e7f33a2570f9e361bb2 to your computer and use it in GitHub Desktop.
PoC List of Try
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
package fp; | |
import io.vavr.control.Try; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
import java.util.stream.Stream; | |
public class PocTry { | |
private static Random random = new Random(); | |
private static String buildString(int i) { | |
if (random.nextBoolean()) { | |
return String.valueOf(i); | |
} else { | |
throw new RuntimeException("error for " + i); | |
} | |
} | |
private static List<String> build() { | |
return IntStream.range(0, 20) | |
.mapToObj(i -> Try.of(() -> buildString(i))) | |
.flatMap(t -> { | |
if (t.isFailure()) { | |
System.out.println(t.getCause().getMessage()); | |
return Stream.empty(); | |
} else { | |
return Stream.of(t.get()); | |
} | |
}).collect(Collectors.toList()); | |
} | |
public static void main(String... args) { | |
build().forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example using http://vavr.io
Explanation:
flatMap
operates onIterable
instances. So collection can flatMap elements of typeTry
,Option
, all java/vavr collections etc.toJavaList
returns ajava.util.List
instance in O(n)asJava()
andasJavaMutable()
, which return immutable/mutable views of typejava.util.List
in O(1)