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


Try this solution, it works correctly.



List<Integer> exampleInts = new ArrayList<>(Arrays.asList(1, 2, 3, 5,
            8, 13, 21));
    int size = (exampleInts.size()-1)*2;
    for (int i = 0; i < size; i+=2) {
        int delimiter = 0;
        exampleInts.add(i+1, delimiter);
    }
    System.out.println(exampleInts);

      

0


source







All Articles