Request for binary search using functions
Julian Hyde
julianhyde at gmail.com
Thu Dec 13 22:23:20 PST 2012
On Dec 12, 2012, at 1:49 AM, Peter Levart <peter.levart at gmail.com> wrote:
> Like that?
Almost what I was after, but not quite. I was looking for something that could implement any kind of abstract list, not just one based on an array.
The problem is that AbstractList has two abstract functions, and a lambda only has one. But I find that whenever I create an AbstractList its size is fixed at create time, and this is true here also. So, let's define a library method that takes a size and a gettable and returns a list:
interface Gettable<T> {
T get(int i);
}
private static abstract class RandomAccessAbstractList<E>
extends AbstractList<E>
implements RandomAccess {}
public static <T> List<T> list(final int size, final Gettable<T> gettable) {
return new RandomAccessAbstractList<T>() {
public T get(int index) {
return gettable.get(index);
}
public int size() {
return size;
}
};
}
Assuming that the list() method is part of a standard library (anyone on this list feel like adding it?!), the binary search problem can now be solved in one line:
SimpleDateFormat[] array;
String seek;
return Collections.binarySearch(list(array.length, (i) -> array[i].toPattern()), seek);
Julian
More information about the lambda-dev
mailing list