如何在Ascending order android中对ArrayList <object>进行排序

时间:2015-08-22 20:59:26

标签: java android sorting arraylist collections

我需要根据名称按升序排序ArrayList<Object>(自定义对象)。为此,我使用比较器方法,如

我的ArrayList:

ArrayList<Model> modelList = new ArrayList<Model>();

我正在使用的代码:

   Comparator<Model> comparator = new Comparator<Model>() {
            @Override
            public int compare(CarsModel lhs, CarsModel rhs) {

                String  left = lhs.getName();
                String right = rhs.getName();

                return left.compareTo(right);

            }
        };

   ArrayList<Model> sortedModel = Collections.sort(modelList,comparator);

//While I try to fetch the sorted ArrayList, I am getting error message 

我完全陷入困境,真的不知道如何继续进行以获得ArrayList<Object>的排序列表。请帮我解决一下这个。任何帮助和解决方案对我都有帮助。我发布了我的确切场景供您参考。提前谢谢。

示例:

ArrayList<Model> modelList = new ArrayList<Model>();
modelList.add(new Model("chandru"));
modelList.add(new Model("mani"));
modelList.add(new Model("vivek"));
modelList.add(new Model("david"));

普通列表:

for(Model mod : modelList){
  Log.i("names", mod.getName());
}

输出

chandru
mani
vivek
david

排序后我的要求如下:

for(Model mod : modelList){
  Log.i("names", mod.getName());
}

输出

chandru
david
mani
vivek

3 个答案:

答案 0 :(得分:37)

你的方法是对的。在下面的示例中创建Comparator内部(或者您可以创建一个新类):

ArrayList<Model> modelList = new ArrayList<>();
modelList.add(new Model("chandru"));
modelList.add(new Model("mani"));
modelList.add(new Model("vivek"));
modelList.add(new Model("david"));

Collections.sort(modelList, new Comparator<Model>() {
    @Override
    public int compare(Model lhs, Model rhs) {
        return lhs.getName().compareTo(rhs.getName());
    }
});

输出

chandru
david
mani
vivek

答案 1 :(得分:4)

 Collections.sort(actorsList, new Comparator<Actors>() {
      @Override
      public int compare(Actors lhs, Actors rhs) {
       return lhs.getName().compareTo(rhs.getName());
     }
    });

答案 2 :(得分:0)

from multiprocessing.pool import ThreadPool
from database import DB_ENGINE, DB_SESSION, db_session

def worker_func(data):
    with db_session(DB_SESSION) as session:
        [...database operations using session object...]

if __name__ == '__main__':
    try:
        data = [1,2,3,4,5]
        with ThreadPool(processes=5) as thread_pool:
            results = thread_pool.map(worker_func, data)
    except:
        raise
    finally:
        # Cleanup
        DB_ENGINE.dispose()