Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

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
...