1

The use case is an efficient way to sort a List of custom objects say

class oC extends A{
  int id;
  ArrayList ocR;
}

class ocR extends A{
  @Override
  public int hashCode() {
    return super.hashCode();
  }

  @Override
  public boolean equals(Object o) {
    return super.equals(o);
  }
} 

ArrayList ocR for each object of oC must also be in sorted order.

The current solution is I have created a sort function which implements a Comparator

sort(List items){
  Collections.sort(items, new Comparator(){ //Logic for comparator by 
                                              overriding compare(A a, A b)} 
}

and then I use the following code

List Oc comments;
for(int index=0;index<comments.size();index++){
   //This is for sorting ArrayList ocR of each oC object
   this.sort(comments.get(index).getocRs());
}
//This is for sorting List of oC
this.sort(comments);`

Is there a way to do away with the for loop without implementing the compartor on oC or oCR class?

Jens
  • 67,715
  • 15
  • 98
  • 113

2 Answers2

3

If you are using Java 8 you can do the following:

comments.forEach(oc -> sort(oc.getocRs()))
Lorelorelore
  • 3,335
  • 8
  • 29
  • 40
  • Isn't it just the concise form of whatever I have already implemented. How is this more efficient that whatever is already implemented by me? – Souvik Sarkhel Nov 28 '18 at 13:14
  • I thought that you wanted a concise form. If you want more efficiency maybe you should evaluate to use a `SortedSet` along the `Comparable` interface instead of a `List` and `Comparator`. – Lorelorelore Nov 28 '18 at 13:29
0

List maintains insertion orders . For more details : Why is there no SortedList in Java?

Instead of List try using TreeSet so the objects are persisted in order

Abdul Shameer
  • 83
  • 2
  • 9
  • Even if this solves the issue of not having to sort the objects after retrieving this will increase the cost of updating the objects which are already persisited as every time for appending all the existing objects need to be retrieved first and then new object needs to be appended. – Souvik Sarkhel Nov 28 '18 at 13:21
  • Are you expecting the list to be sorted after adding the values ? Then obviously you need to use Collection method Sort() to sort in order at desired order. incase if you need to sort the objects while adding then Treeset will be better option. – Abdul Shameer Nov 29 '18 at 05:53