fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.util.function.*;
  5.  
  6. class Ideone
  7. {
  8. public static void main (String[] args) throws java.lang.Exception
  9. {
  10. StringUtil.indexOf("hello, world", 'l')
  11. .DoIfSuccess(foundIndex -> {
  12. System.out.println(String.format("index=%d", foundIndex));
  13. });
  14. }
  15. }
  16.  
  17. class StringUtil {
  18. public static Maybe<Integer> indexOf(String haystack, char needle) {
  19. for (int i = 0; i < haystack.length(); ++i)
  20. if (haystack.charAt(i) == needle)
  21. return Maybe.<Integer>just(i);
  22. return Maybe.<Integer>nothing();
  23. }
  24. }
  25.  
  26. class Maybe<ResultType> {
  27. public static <R> Maybe<R> nothing() {
  28. return new Maybe(false, null);
  29. }
  30.  
  31. public static <R> Maybe<R> just(R resultValue) {
  32. return new Maybe(true, resultValue);
  33. }
  34.  
  35. private final boolean isSucceeded;
  36. private final ResultType resultValue;
  37.  
  38. private Maybe(boolean isSucceeded, ResultType resultValue) {
  39. this.isSucceeded = isSucceeded;
  40. this.resultValue = resultValue;
  41. }
  42.  
  43. public void DoIfSuccess(Consumer<ResultType> postAction) {
  44. if (isSucceeded && postAction != null)
  45. postAction.accept(resultValue);
  46. }
  47. }
Success #stdin #stdout 0.14s 2184192KB
stdin
Standard input is empty
stdout
index=2