Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to rearrange an ArrayList in Java

Tags:

java

list

What is the best way to rearrange elements in an list? I need the ability to move elements to move elements in the list, one step back or forward in the index. I was thinking of getting the index of the item, adding it at index -1 / +2 and removing the old reference.

Is there a faster way to handle rearranging without creating duplicates in the list in the process.

like image 246
Jens Jansson Avatar asked Mar 18 '09 09:03

Jens Jansson


People also ask

How do you rearrange ArrayList in Java?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.

How do you put an ArrayList in alphabetical order?

To sort the ArrayList, you need to simply call the Collections. sort() method passing the ArrayList object populated with country names. This method will sort the elements (country names) of the ArrayList using natural ordering (alphabetically in ascending order).

How do you sort an ArrayList in a natural order?

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.


1 Answers

Use the JDK's swap method

The JDK's Collections class contains a method just for this purpose called Collections.swap. According to the API documentation this method allows you to "swap the elements at the specified positions in the specified list."

I suggest this solution so that you don't have to remove elements from the List and so that you don't have to roll your own swap method. Also, it looks like this method has been around since the 1.4 release of Java so it should work for most of the modern JDKs.

like image 76
Elijah Avatar answered Sep 28 '22 07:09

Elijah