Skip to content

Instantly share code, notes, and snippets.

@jwgmeligmeyling
Created December 27, 2017 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwgmeligmeyling/6f7adeed0b0c92c1df81e204a2917676 to your computer and use it in GitHub Desktop.
Save jwgmeligmeyling/6f7adeed0b0c92c1df81e204a2917676 to your computer and use it in GitHub Desktop.
ComparatorUtil.java
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