Insert an item between each list item
Is there a better way to insert an element between every pair of elements in a list in Java than iterating through it
List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1,2,3,5,8,13,21));
for (int i = 1; i < exampleInts.size(); i++) {
int delimiter = 0;
exampleInts.add(i, delimiter);
i++;
}
+3
source to share
2 answers
No, there are no utils out of the box in the standard java libraries.
By the way, your loop is wrong and will run indefinitely until the end of memory. You have to increment the i
variable one more time:
for (int i = 1; i < exampleInts.size(); i++) {
int delimiter = 0;
exampleInts.add(i, delimiter);
i++;
}
or change the loop conditions to for (int i = 1; i < exampleInts.size(); i+=2) {
+3
source to share