Lemon
Lemon

Reputation: 97

Java: duplicate ArrayList items in order of insertion

Have two methods, main and twoTimes that takes in a single parameter (ArrayList) but returns the said ArrayList doubled and in order.

I have twoTimes repeating the variables within the parameters but it's coming out (1,5,3,7,1,5,3,7) instead of (1,1,5,5,3,3,7,7).

import java.lang.reflect.Array;
import java.util.ArrayList;

class Main {

     public static void main(String[] args) {
          ArrayList<Integer> nums = new ArrayList<>();
          nums.add(1);
          nums.add(5);
          nums.add(3);
          nums.add(7);

          twoTimes(nums);
     }
    
     public static ArrayList<Integer> twoTimes(ArrayList nums) {
          ArrayList<Integer> newNems = new ArrayList<>(nums);

          newNems.addAll(nums);

          System.out.println(newNems);
          return newNems;
    }

}

Upvotes: 1

Views: 64

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19575

You could be using Stream API flatMap to duplicate each element in the input list:

public static List<Integer> duplicateElements(List<Integer> input) {
    return input.stream()
                .flatMap(i -> Stream.of(i, i)) // getting stream of duplicate elements
                .collect(Collectors.toList());
}

Simple test:

System.out.println(duplicateElements(Arrays.asList(1, 3, 5, 7)));

Output:

[1, 1, 3, 3, 5, 5, 7, 7]

More general method generating num copies of each element:

public static List<Integer> multiplyElements(List<Integer> input, int num) {
    return input.stream()
                .flatMap(i -> IntStream.range(0, num).mapToObj(n -> i)) // getting stream of multiple elements
                .collect(Collectors.toList());
}

Upvotes: 1

Majed Badawi
Majed Badawi

Reputation: 28434

You can iterate over nums and add each item twice to the new list:

public static ArrayList<Integer> twoTimes(ArrayList<Integer> nums) {
    ArrayList<Integer> newNems = new ArrayList<>();

    for(int i = 0; i < nums.size(); i++) {
        int num = nums.get(i);
        newNems.add(num);
        newNems.add(num);
    }

    System.out.println(newNems);
    return newNems;
}

Upvotes: 1

Related Questions