Skip to content

Instantly share code, notes, and snippets.

@ygrenzinger
Created July 14, 2017 09:18
Show Gist options
  • Save ygrenzinger/f88e160ab7d70e7f33a2570f9e361bb2 to your computer and use it in GitHub Desktop.
Save ygrenzinger/f88e160ab7d70e7f33a2570f9e361bb2 to your computer and use it in GitHub Desktop.
PoC List of Try
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);
}
}
@danieldietrich
Copy link

danieldietrich commented Jul 14, 2017

Example using http://vavr.io

import io.vavr.collection.Iterator; // could be also any other collection, including List, Vector, Stream, Queue, ...
import io.vavr.control.Try;
import static io.vavr.API.*; // for println shortcut

Iterator.range(0, 20)
    .map(i -> Try.of(() -> buildString(i)))
    .flatMap(t -> t.onFailure(x -> println(x.getMessage())))
    .toJavaList();

Explanation:

  • flatMap operates on Iterable instances. So collection can flatMap elements of type Try, Option, all java/vavr collections etc.
  • toJavaList returns a java.util.List instance in O(n)
  • if the collection is a Seq (like List, Vector, Stream, Array, ...), there are methods asJava() and asJavaMutable(), which return immutable/mutable views of type java.util.List in O(1)

@ygrenzinger
Copy link
Author

Thanks !

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