集合排序和二进制搜索以及 lambda 比较器

Collections Sort and Binarysearch and lambda comparator

我有一个对象 Customer,其属性 id 是一个 int。我正在尝试使用带有 lambda 比较器的 Collections 内置排序和搜索功能。我的问题是,为什么这似乎有效:

Collections.sort(customers, (a, b) -> a.getID() - b.getID());

但这不是:

foundIndex = Collections.binarySearch(customers, custID, 
                    (a, b) -> a.getID() - b.getID());

当我说 'seem to work' 时,我的意思是它运行没有错误。 特别是第二行,Eclipse 有一个问题 .getID() 。它给了我一个选角建议,我试过了:

foundIndex = Collections.binarySearch(customers, custID, 
                    (a, b) -> ((Customer) a).getID() - ((Customer) b).getID());

但是 运行 出现运行时错误,提示“无法将整数转换为 class 客户” 当我尝试在 (a, b) 内部进行转换时,Eclipse 也不喜欢那样。 任何 lambda 都会在 binarySearch 部分执行我想要的操作吗?

正如评论者 Silvio Mayolo 所说,问题不在于 lambda,而是 Collections.binarySearch().

中关键参数所预期的问题

这完全符合我的要求:

//assumes presorted customers ArrayList, thank you commenter gOOse
public Customer findCustomer(int custID) {
        int foundIndex;
        Customer key = new Customer(custID, null);
        
        readLock.lock();
        try {
            foundIndex = Collections.binarySearch(customers, key, 
                (a, b) -> a.getID() - b.getID());       
            return (foundIndex > -1) ? customers.get(foundIndex) : null;
        }
        finally { readLock.unlock(); }
    }

您是否尝试过提供客户实例 class 而不是 ID?

foundIndex = Collections.binarySearch(customers, customer, 
                    (a, b) -> a.getID() - b.getID());