Created
May 8, 2015 07:14
-
-
Save amaembo/806f6cefa90329a8a060 to your computer and use it in GitHub Desktop.
Try monad example (requires com.jasongoodwin.monads)
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 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