Created
May 28, 2015 05:55
-
-
Save kariyayo/2bcd55eda494290b20e0 to your computer and use it in GitHub Desktop.
OptionalのflatMap
This file contains hidden or 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
public class Main { | |
public static void main(String[] args) { | |
System.out.println(flatMapRoutine()); | |
System.out.println(nonFlatMapRoutine()); | |
} | |
private static Optional<Pole> flatMapRoutine() { | |
return new Pole(0, 0).landLeft(1) | |
.flatMap(x -> x.landRight(4)) | |
.flatMap(x -> x.landLeft(-1)) | |
.flatMap(x -> x.landRight(-2)); | |
} | |
private static Optional<Pole> nonFlatMapRoutine() { | |
Optional<Pole> result; | |
Optional<Pole> pole1 = new Pole(0, 0).landLeft(1); | |
if (pole1.isPresent()) { | |
Optional<Pole> pole2 = pole1.get().landRight(4); | |
if (pole2.isPresent()) { | |
Optional<Pole> pole3 = pole2.get().landLeft(-1); | |
if (pole3.isPresent()) { | |
result = pole3.get().landRight(-2); | |
} else { | |
result = Optional.empty(); | |
} | |
} else { | |
result = Optional.empty(); | |
} | |
} else { | |
result = Optional.empty(); | |
} | |
return result; | |
} | |
} |
This file contains hidden or 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
public class Pole { | |
private int left; | |
private int right; | |
public Pole(int left, int right) { | |
this.left = left; | |
this.right = right; | |
} | |
public Optional<Pole> landLeft(int n) { | |
if (Math.abs(left + n - right) < 4) { | |
left = left + n; | |
return Optional.of(this); | |
} else { | |
return Optional.empty(); | |
} | |
} | |
public Optional<Pole> landRight(int n) { | |
if (Math.abs(right + n - left) < 4) { | |
right = right + n; | |
return Optional.of(this); | |
} else { | |
return Optional.empty(); | |
} | |
} | |
@Override | |
public String toString() { | |
return "Pole{" + | |
"left=" + left + | |
", right=" + right + | |
'}'; | |
} | |
@Override | |
public boolean equals(Object o) { | |
if (this == o) return true; | |
if (o == null || getClass() != o.getClass()) return false; | |
Pole pole = (Pole) o; | |
if (left != pole.left) return false; | |
if (right != pole.right) return false; | |
return true; | |
} | |
@Override | |
public int hashCode() { | |
int result = left; | |
result = 31 * result + right; | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment