Skip to content

Instantly share code, notes, and snippets.

@amaembo
Created May 8, 2015 07:14
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 amaembo/806f6cefa90329a8a060 to your computer and use it in GitHub Desktop.
Save amaembo/806f6cefa90329a8a060 to your computer and use it in GitHub Desktop.
Try monad example (requires com.jasongoodwin.monads)
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.jasongoodwin.monads.Try;
public class TryTest {
public static String doStuff(String s) {
if(s.startsWith("a")) {
throw new IllegalArgumentException("Incorrect string: "+s);
}
return s.trim();
}
public static void main(String[] args) {
List<String> input = Arrays.asList("aaa", "b", "abc ", " qqq ");
Map<Boolean, List<Try<String>>> result = input.stream()
.map(Try::successful).map(t -> t.map(TryTest::doStuff))
.collect(Collectors.partitioningBy(Try::isSuccess));
System.out.println(result.get(true).stream().map(t -> t.orElse(null))
.collect(Collectors.joining(",")));
result.get(false).stream().forEach(t -> t.onFailure(System.out::println));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment