Skip to content

Instantly share code, notes, and snippets.

@kariyayo
Created May 28, 2015 05:55
Show Gist options
  • Save kariyayo/2bcd55eda494290b20e0 to your computer and use it in GitHub Desktop.
Save kariyayo/2bcd55eda494290b20e0 to your computer and use it in GitHub Desktop.
OptionalのflatMap
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;
}
}
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