Which of the following two methods would be the faster one of keeping an ArrayList
sorted ?
- Inserting the element in its place
- Calling
push
, then callCollections.sort(myList)
Which of the following two methods would be the faster one of keeping an ArrayList
sorted ?
push
, then call Collections.sort(myList)
There is different kinds of collections. You could choose one that keeps your data sorted.
It would probably be more efficient to insert in the right position, for example by using Collections.binarySearch(list, elementToInsert)
:
int index = Collections.binarySearch(list, element);
if (index < 0) index = - (index + 1);
list.add(index, element);
If you don't need random access and your entries are unique (which seems to be the case based on your comment), you could also use a TreeSet:
NaivigableSet<User> users = new TreeSet<> (Comparator.comparing(User::getId));
The set will always be sorted based on the user ids which must be unique.
If your requirement asks for a continuous sorting after every insert, i think you should try alternate approach than the current one as this in itself is not time efficient. For a elaborate explanation for possible solution you must look at Sorted array list in Java