-1

is it possible to generate an already existing list (filled with names, for example) in a new order?

So the list is filled as follows:

ArrayList<String> playerNames =  new  ArrayList<String>();

for (int n = 0; n < 5; n++) 
{       
     String name = "Player"+i;
     playerNames.add(name);
}

Now the first one in the list is "Player0".

Is it now possible to start this list with a new random number? So like the following example:

Player0
Player1
Player2
Player3
Player4

becomes

Player3
Player4
Player0
Player1
Player2

So the order of the list should be kept, only the first in the list should be changed (and of course all following ones)

I hope you understand what I mean by that.

Hansi
  • 97
  • 3
  • 13
  • Yes it is possible, why not try yourself? – Joakim Danielson Nov 11 '20 at 14:56
  • 1
    Could you clarify "generate an already existing list (..) in a new order"? Do you want to (A) reorder elements *in already existing list*, or (B) create *separate* list which will hold elements from already existing list but in different order? – Pshemo Nov 11 '20 at 14:57
  • hey, oh of course sorry. create a seperate list with the different order – Hansi Nov 11 '20 at 15:11

1 Answers1

1

Here is a simple code how you can achieve it. Set an index from which you want to start. First loop from index till end of list and after that from zero to index.

Another hint initialize variable to interface "List" instead of "ArrayList"

     List<String> playerNames = new ArrayList<String>();

    for (int n = 0; n < 5; n++) {
        String name = "Player" + n;
        
        playerNames.add(name);
    }


    int index = 2;
    
    List<String> newOrder = new ArrayList<>();
    for (int n=index; n < playerNames.size(); n++) {
        
        newOrder.add(playerNames.get(n));
    }

    for (int n=0; n < index; n++) {
        
        newOrder.add(playerNames.get(n));
    }
    for (String s : newOrder) {
        System.out.println(s);
    }
devadrion
  • 216
  • 2
  • 6
  • Ok that is working for me! Awesome. Thank you so much. My thoughts were too complex...but that in the end it is so simple :/ Thanks! – Hansi Nov 11 '20 at 15:29
  • 1
    You are welcome :) the solution is often easier than we thought. – devadrion Nov 11 '20 at 15:33