How to print array elements in groups of 2 with Java

2 Answers

0 votes
public class GroupArrayElements {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7};

        for (int i = 0; i < array.length; i += 2) {
            if (i + 1 < array.length) {
                System.out.println(array[i] + ", " + array[i + 1]);
            } else {
                System.out.println(array[i]); // Handle the last element if the array length is odd
            }
        }
    }
}


 
/*
run:
 
1, 2
3, 4
5, 6
7
 
*/

 



answered Jun 20, 2025 by avibootz
0 votes
import static java.lang.System.out;
import static java.util.stream.IntStream.range;

public class GroupArrayElements {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8};

        range(0, array.length - 1)
            .filter(i -> i % 2 == 0)
            .mapToObj(i -> array[i] + ", " + array[i + 1])
            .forEach(out::println);
    }
}


 
/*
run:
 
1, 2
3, 4
5, 6
7, 8
 
*/

 



answered Jun 20, 2025 by avibootz
...