0

I need to keep the order of my list of objects as it can be changed and reordered anytime in my webapp.

In my model I have a array list of objects example

objectList = [object1, object2, object3, object4]

and I save the order of each object belonging to this instance to a Map example: order

{
   "object1":4,
   "object2":2,
   "object3":1,
   "object4":3
}

Therefore i want to sort my array according to its value in the map retrieved by the objects Id as the key:

Expected result:

[object3, object2, object4, object1]

How would I go about doing this?

Dean Strydom
  • 275
  • 5
  • 17
  • 3
    Do you mean something like this: `objectList.sort(Comparator.comparing(o -> yourMap.get(o.getid()));`? – Lino Apr 14 '20 at 10:10
  • you can try to read this article. I think the answer here https://stackoverflow.com/questions/8119366/sorting-hashmap-by-values – Zeroes Apr 14 '20 at 10:18
  • @Lino Boy that was quick. Yes this works great thank you. Can you post it as an answer so I can accept it – Dean Strydom Apr 14 '20 at 10:20

2 Answers2

2

Assuming your objects have a getter for the id getId(), then you can make use of the Comparator.comparing() helper method, which creates a comparator for the provided lambda:

objectList.sort(Comparator.comparing(o -> yourMap.get(o.getId()));

This effectively the same as writing your own Comparator or writing your own compare method.

Lino
  • 19,604
  • 6
  • 47
  • 65
0

Something that may look overkilling but it could be more natural to define a new class

class IndexedElement implments Comparable<Integer> {
    private final int index;
    private final YourObject element;

    public IndexedElement(int index, YourObject element) {
       this.index = index;
       this.element = element;
    }

    @Override
    public int compareTo(Integer o) {
       return this.getIndex().compareTo(o.getIndex()) ;
    }
}

storing objects like that in a TreeSet<IndexedElement> you can automatically achieve the sorting and retrieving (TreeSet.ceiling(new IndexedElement(yourIndex, null)), just remember to Override the equals/hashCode in IndexedElement)

user2688838
  • 761
  • 5
  • 11