Created
January 21, 2017 11:16
-
-
Save danieldietrich/dd5a64c6b174f1144d40dae9a942e8d1 to your computer and use it in GitHub Desktop.
Inserting objects into a database and collecting the errors (Java vs Javaslang)
This file contains 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
import javaslang.control.Try; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import static javaslang.API.*; | |
public class Test { | |
public static void main(String[] args) { | |
java.util.List<Person> persons1 = Arrays.asList(new Person("Andy"), new Person("Emil"), new Person("Annabel")); | |
// [java.lang.RuntimeException: Andy, java.lang.RuntimeException: Annabel] | |
System.out.println(plainJavaTest(persons1)); | |
javaslang.collection.List<Person> persons2 = List(new Person("Andy"), new Person("Emil"), new Person("Annabel")); | |
// = List(java.lang.RuntimeException: Andy, java.lang.RuntimeException: Annabel) | |
System.out.println(javaslangTest(persons2)); | |
} | |
static java.util.List<Exception> plainJavaTest(java.util.List<Person> persons) { | |
java.util.List<Exception> errors = new ArrayList<>(); | |
persons.forEach(person -> { | |
try { | |
MongoDB.insert(person); | |
} catch(Exception x) { | |
errors.add(x); | |
} | |
}); | |
return errors; | |
} | |
static javaslang.collection.List<Throwable> javaslangTest(javaslang.collection.List<Person> persons) { | |
return persons.flatMap(person -> Try.run(() -> MongoDB.insert(person)).failed()); | |
} | |
} | |
interface MongoDB { | |
static void insert(Person person) { | |
if (person.name.startsWith("A")) { | |
throw new RuntimeException(person.name); | |
} | |
} | |
} | |
class Person { | |
final String name; | |
Person(String name) { | |
this.name = name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment