前言
项目中遇到一个需求:一个对象集合是排好序的,对象里有一个字段是日期类型,给出一个日期找到集合对象中的日期字段和给出的日期相等或最相近且小于目标日期的对象。
本着能不造轮子就不造轮子的原则把apache commons
,guava
等相关类库找了一圈,但没找到符合我需求的,百度出来都不如JDK自带的,只能动手撸一个了。
Code
public class CollectionUtils extends org.apache.commons.collections.CollectionUtils {
/**
* 二分查找模式
*/
public enum BinarySearchMode {
// 只匹配相等
EQUALS,
// 先匹配相等,找不到再匹配相似且大于目标值
LIKE_GREATER_THAN,
// 先匹配相等,找不到再匹配相似且小于目标值
LIKE_LESS_THAN;
public <E, T extends Comparable<T>> E handle(List<E> collection, Function<E, T> extract, T target, int center) {
E element = collection.get(center);
int cmp = extract.apply(element).compareTo(target);
return handle(collection, cmp, center);
}
public <E, T> E handle(List<E> collection, Function<E, T> extract, T target, int center, Comparator<T> comparator) {
E element = collection.get(center);
int cmp = comparator.compare(extract.apply(element), target);
return handle(collection, cmp, center);
}
private <E> E handle(List<E> collection, int cmp, int center) {
if (this == BinarySearchMode.LIKE_GREATER_THAN) {
if (isLast(collection, center) && cmp < 0) {
return null;
}
return collection.get(center);
}
if (this == BinarySearchMode.LIKE_LESS_THAN)