1

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;
    }

}
1
  • 1
    May be worth verifying that 'doubled' in this context actually means making a second copy of the array elements (resulting in [1,1,3,3,5,5,7,7]) as opposed to, say, doubling the value of each array element (resulting in [2,6,10,14]). Commented Oct 18, 2020 at 21:13

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

That sorts them in order, I would need them to be in the specific order that is put in the original parameters, this is a really cool trick though I will keep in mind.
@DylanStocking you mean 1,1,5,5,3,3,7,7?
@DylanStocking I updated the answer. Please modify the question.
That's perfect!
@DylanStocking Please mark the answer as the solution to close the question
1

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.