3

Here I give a heterogeneous arraylist. I need sort there arraylist to Assenting & Descending order respectively.

Model model;
String[] arr={"A2","4","2","1","A3","3","A1"};

ArrayList<Model> list=new ArrayList<>;
for(int i=0;i<arr.length();i++){
    model=new Model();
    model.setBookNum(arr[i]);
    model.setBookPos(i);
    list.add(model);
} 

This is Model Class

public class Model {
private  String  BookNum="";
private  int BookPos="";

   public String getBookNum() {
       return BookNum;
   }

   public void setBookNum(String bookNum) {
       BookNum = bookNum;
   }

   public String getBookPos() {
       return BookPos;
   }

   public void setBookPos(String bookPos) {
       BookPos = bookPos;
   }
}

And Expected result in Assenting order is 1, 2, 3, 4, A1, A2, A3 & Descending order is A3, A2, A1, 4, 3, 2, 1.

Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
  • First - You need to create a new object each time you add to the list. Second - You can achieve sorting by making the Model class Comparable ```class Model implements Comparable{ ``` then override the toCompare() method like this to acheive ascending order sort ```@Override public int compareTo(Model model) { return this.getBookNum().compareTo(model.getBookNum()); }``` Now this ```Collections.sort(list);``` will sort the list in ascending order. Swaping the objects in compareTo() method will sort in descending order. – JavaYouth Sep 08 '17 at 05:43
  • @JavaYouth If In model class multiple items then how to sort. I just **edit** question. Because In **Model Class** I have multiple items. & I have apply `Collections.sort(list);` then output is **`Undefined`** – Shivam Kumar Sep 08 '17 at 06:00
  • Usually, we sort objects by any of its properties. For instance: if I have an Employee object having id & name as its properties. I either sort it by id OR sort by name. Although you can write your own logic in compareTo() method, sorting with multiple properties of an object does not give expected results. – JavaYouth Sep 08 '17 at 07:40

1 Answers1

2

Do it like this.

//Sorts the list ascending order
Collections.sort(list);

//Reverses the sorted list so it is effectively Descending order
Collections.reverse(list);
Supun Amarasinghe
  • 1,443
  • 3
  • 12
  • 24