I have a List containing elements that are accessed according to their indexes. In this list I need to be able to “rotate” groups of 4 elements according to their index. For example in the list
[a, b, c, d, e ,f , g, h, i, j, k, l]
I want to rotate c, f, i, l in order to get
[a, b, l, d, e ,c , g, h, f, j, k, i]
How will you implement this ?
A straightforward solution
If you only need to 1-rotate elements at 4 indices of a
List, you can just write a straightforward generic method like this:This will cyclically rotate 4 elements of any
List<T>. Remember thatList.setreturns the element that previously was at that index, so you could write the entire method in one-line if you want:With this helper method, you’ll have:
A more general solution
IF you need a way to rotate an arbitrary number of elements for an arbitrary distance, then you can create a live view of another
List, and then you canCollections.rotatethat view.IF the elements are consecutive, for example, you’d just use
subList:Since the elements aren’t consecutive, you can’t use
subList, but you can write e.g.PeriodicalLiveViewListclass. You want to be able to write something like this:Basically you create another
Listwhose elements are every 3rd element of anotherList, starting at index 2, as a live view.If you are using Guava, there is
ForwardingListthat you can built on. You can implement the decorator pattern for this from scratch too if necessary.Related questions