rares985
rares985

Reputation: 391

What is the most efficient way (speed-wise) of maintaining a sorted ArrayList in Java?

Which of the following two methods would be the faster one of keeping an ArrayList sorted ?

Upvotes: 1

Views: 102

Answers (3)

assylias
assylias

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

pradex
pradex

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

smonff
smonff

Reputation: 3497

There is different kinds of collections. You could choose one that keeps your data sorted.

Upvotes: 3

Related Questions