Last active
November 30, 2017 22:19
-
-
Save dmolesUC/bcb74faee46d39082fc296c1254c2fab to your computer and use it in GitHub Desktop.
Java compareTo() in functional style
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 io.vavr.collection.Array; | |
import java.net.URI; | |
import java.util.Objects; | |
import java.util.function.IntSupplier; | |
import java.util.stream.Stream; | |
class Vocab implements Comparable<Vocab> { | |
private final String prefix; | |
private final URI uri; | |
private final Array<String> terms; | |
// ... | |
@Override | |
public int compareTo(Vocab o) { | |
Objects.requireNonNull(o); | |
if (o == this) { | |
return 0; | |
} | |
return Stream.<IntSupplier>of( | |
() -> prefix.compareTo(o.prefix), | |
() -> uri.compareTo(o.uri), | |
() -> Integer.compare(terms.length(), o.terms.length()), | |
() -> terms.toStream().zip(o.terms.toStream()) | |
.toJavaStream() | |
.mapToInt(t -> t._1.compareTo(t._2)) | |
.filter(i -> i != 0).findFirst().orElse(0) | |
).mapToInt(IntSupplier::getAsInt) | |
.filter(i -> i != 0).findFirst().orElse(0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment