简体   繁体   中英

How to sort ArrayList<Object> in Ascending order android

I have a requirement to sort ArrayList<Object> (Custom objects) in Ascending order based upon name. For that purpose I am using comparator method as like

My ArrayList :

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

Code I am using:

   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 

I am completely stuck up and really dont know how to proceed further in order to get sorted list of ArrayList<Object> . Please help me with this. Any help and solutions would be helpful for me. I am posting my exact scenario for your reference. Thanks in advance.

Example:

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"));

Normal List:

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

Output :

chandru
mani
vivek
david

My requirement after sorting to be like:

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

Output :

chandru
david
mani
vivek

Your approach was right. Make your Comparator inner like in the following example (or you can create a new class instead):

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

output :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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