I need to distribute ArrayList< String >
into two other ArrayList< String >
's
So basically I have one ArrayList
named players
ArrayList< String > players = new ArrayList<>();
And then I have two other ArrayList
s named teamBlue
and teamRed
ArrayList< String > teamBlue = new ArrayList<>();
ArrayList< String > teamRed = new ArrayList<>();
And basically I need to somehow be able to go through the players
list and distribute the contents evenly (sometimes players.size()
will not be an even number, but it's fine to have not 100% even distribution)
I appreciate any help that you can give me, thank you!
You can use a foreach with a counter. When the counter is even, add the corresponding String to an ArrayList, when it's not add it to the other one.
int counter = 0;
for(String s : players){
//check the value of the counter and add the String to the corresponding list
//increment the counter
}
You could also use a traditional for loop (using get
on the ArrayList
with the index), but I prefer a foreach as it uses an Iterator
behind the scenes so you don't depend of the current List
implementation (and can improve performance, ex. O(n²)
for a LinkedList
instead of O(n)
for an ArrayList
)
Just cut the list in half, right in the middle. No need to iterate through the list.
int length = players.size();
List<String> teamBlue = players.subList(0, length / 2);
List<String> teamRed = players.subList(length / 2, length);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.