Reputation: 391
Which of the following two methods would be the faster one of keeping an ArrayList
sorted ?
push
, then call Collections.sort(myList)
Upvotes: 1
Views: 102
Reputation: 328923
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.
Upvotes: 2
Reputation: 348
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
Upvotes: 0
Reputation: 3497
There is different kinds of collections. You could choose one that keeps your data sorted.
Upvotes: 3