I have an object Customer with an attribute id that is an int. I'm trying to use Collections builtin sort and search features with a lambda comparator. My question is, why does this seem to work:
Collections.sort(customers, (a, b) -> a.getID() - b.getID());
But this does not:
foundIndex = Collections.binarySearch(customers, custID,
(a, b) -> a.getID() - b.getID());
When I say 'seem to work' I mean it runs with no errors.
Specifically with the second line, Eclipse has a problem with .getID() . It gave me a casting suggestion, which I tried:
foundIndex = Collections.binarySearch(customers, custID,
(a, b) -> ((Customer) a).getID() - ((Customer) b).getID());
But that ran into a runtime error that said "Integer can not be cast to class Customer"
When I try to cast inside the (a, b) Eclipse doesn't like that either.
Will any lambda do what I want in the binarySearch part?
binarySearchexpects a value of the same type as your list elements, so you need to pass it a customer, not a customer's ID. Admittedly, I would be inclined to agree that the API is flawed (accepting a value of the key type makes more sense here), but that's Java for you.