Souvik Sarkhel
Souvik Sarkhel

Reputation: 139

Java Collections and Comparator

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?

Upvotes: 1

Views: 72

Answers (2)

Abdul Shameer
Abdul Shameer

Reputation: 83

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

Upvotes: 0

Lorelorelore
Lorelorelore

Reputation: 3393

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

comments.forEach(oc -> sort(oc.getocRs()))

Upvotes: 3

Related Questions