Java, searching within a list of objects?

后端 未结 6 1910
名媛妹妹
名媛妹妹 2020-12-09 10:49

I\'m a bit lost on the way to make this happen the fastest. I have a large list of objects that have basic variable attributes (with getters / setters) and I need to do a se

6条回答
  •  佛祖请我去吃肉
    2020-12-09 11:27

    Take a look at the binarySearch that takes a comparator:

    public static int binarySearch(List list, T key, Comparator c)

    So you would do something like:

    class FooComparator
        implements Comparator
    {
        public int compare(T a, T b)
        {
            return (a.getName().compareTo(b.getName());
        }
    }
    
    int index = Collections.binarySearch(myList, "value", new FooComparator());
    

    You will need to first sort the list of course (Collections.sort takes a Comaprator as well...).

提交回复
热议问题