Home > OS >  Remove last comma in for loop using array
Remove last comma in for loop using array

Time:05-24

I'm stuck. I'm trying to remove the last comma at the back of the output but I just don't know how.

123, 97, 88, 99, 200, 50,

This is my code below, while checking for highest number in array.

public static void main(String[] args) {
    int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};

    for (int i : array) {
        if (i >= 50) {
            System.out.print(i   ", ");
        }
    }
    System.out.println();
}

CodePudding user response:

One workaround here would be to prepend a comma to all but the first element in the array.

public static void main(String[] args) {
    int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};

    for (int i=0; i < array.length;   i) {
        if (i > 0) {
            System.out.print(", ");
        }
        System.out.print(array[i]);
    }
    System.out.println();
}

This prints:

4, 97, 123, 49, 88, 200, 50, 13, 26, 99

CodePudding user response:

You can use streams:

public static void main(String[] args) {
    int[] array = {4, 97, 123, 49, 88, 200, 50, 13, 26, 99};
    String result = Arrays.stream(array)
                          .boxed()
                          .map(i -> i.toString())
                          .collect(Collectors.joining(", "));
    System.out.println(result);
  • Arrays.stream returns a stream of int
  • boxed converts int (primitive) to Integer (object)
  • map converts Integer to String
  • Collectors.joining concatenates all elements in stream and separates each element with a comma followed by a space, i.e. ,

Running the above code prints the following:

4, 97, 123, 49, 88, 200, 50, 13, 26, 99
  • Related