How to do this using a regex in Java

I had a programming exercise (in Java) and at the end it asked that I take the list of integers and output them, seperated only by one whitespace. I tried doing this with a regex but after an hour I gave up and simply did System.out.print(str1 + " "); which for my case was good enough for now as I am self-studying.

Still, I want to know what I was doing wrong and would like some help. The code is very simple: I have a list of integers the are part of an array list named X

for (int k = 0; k < n; k++) {
    sum += X.get(k);
    //while I was getting the sum I figured i'd get the string as well
    String str1 = Integer.toString(X.get(k));
    //str1.replaceAll("\s+", "s");
    str1 = str1.replaceAll("\s+", " ");
    System.out.print(str1);
}

Again, I am still working on the basics so it’s something that I am missing… I assumed it would replace any whitespace with just one white space after each loop but it outputs no whitespace: 2614306212625451010222046

intended sample output 2 6 14 30 62 126 254 510 1022 2046

Answer

It would be inappropriate to use regex for this.

One way to do this is by printing the delimiter first:

// Start with an empty delimiter, so you don't print a space in front of the
// first number.
String delim = "";
for (int i : X) {
  sum += i;

  System.out.print(delim);
  System.out.print(i);

  // Now set the delimiter to a single space, so a single space will be printed
  // before all elements (except the first).
  delim = " ";
}

It would be easier again to use streams:

sum = X.stream().mapToInt(a -> a).sum();
System.out.println(X.stream().map(Integer::toString).collect(joining(" "));