简体   繁体   English

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

[英]Collections Sort and Binarysearch and lambda comparator

I have an object Customer with an attribute id that is an int.我有一个对象 Customer,其属性 id 是一个 int。 I'm trying to use Collections builtin sort and search features with a lambda comparator.我正在尝试使用带有 lambda 比较器的 Collections 内置排序和搜索功能。 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() .特别是第二行,Eclipse 有.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.但这遇到了一个运行时错误,说“Integer can not be cast to class Customer”当我尝试在(a, b) Eclipse 也不喜欢那样。 Will any lambda do what I want in the binarySearch part?任何 lambda 都会在 binarySearch 部分做我想要的吗?

Have you tried providing an instance of the Customer class instead of an ID?您是否尝试过提供 Customer 类的实例而不是 ID?

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

As commenter Silvio Mayolo stated, the problem isn't really the lambda it is what is expected by the key argument in Collections.binarySearch() .正如评论者 Silvio Mayolo 所说,问题实际上并不是 lambda,而是Collections.binarySearch()的关键参数所期望的。

This works exactly as I wanted:这完全符合我的要求:

//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(); }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM