Created
December 27, 2017 11:57
-
-
Save jwgmeligmeyling/6f7adeed0b0c92c1df81e204a2917676 to your computer and use it in GitHub Desktop.
ComparatorUtil.java
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
package com.pallasathenagroup.util; | |
import java.util.Comparator; | |
import java.util.Optional; | |
/** | |
* Comparator utility methods for handling optional comparable. | |
*/ | |
public class ComparatorUtil { | |
/** | |
* A comparator that sorts present {@code Optional} values first. | |
* | |
* @param <T> the type of the elements to be compared | |
* @param comparator a {@code Comparator} for comparing present values | |
* @return a comparator that considers {@code isPresent} to be lower than | |
* non-present, and compares present objects with the supplied | |
* {@code Comparator}. | |
* @see Comparator#nullsFirst(Comparator) | |
*/ | |
public static <T> Comparator<Optional<T>> presentFirst(Comparator<? super T> comparator) { | |
return (a,b) -> a.map(t1 -> b.map(t -> comparator.compare(t1, t)) | |
.orElse(-1)).orElseGet(() -> b.isPresent() ? | |
1 : 0); | |
} | |
/** | |
* A comparator that sorts present {@code Optional} values last. | |
* | |
* @param <T> the type of the elements to be compared | |
* @param comparator a {@code Comparator} for comparing present values | |
* @return a comparator that considers {@code isPresent} to be higher than | |
* non-present, and compares present objects with the supplied | |
* {@code Comparator}. | |
* @see Comparator#nullsFirst(Comparator) | |
*/ | |
public static <T> Comparator<Optional<T>> presentLast(Comparator<? super T> comparator) { | |
return (a,b) -> a.map(t1 -> b.map(t -> comparator.compare(t1, t)) | |
.orElse(1)).orElseGet(() -> b.isPresent() ? | |
-1 : 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment