You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何循环遍历多个字符串数组按索引分组提取元素并打印

实现方案

要实现多个数组按相同下标分组提取元素,核心是通过数组下标做对齐遍历。你之前用的增强for循环只能遍历单个数组的元素、拿不到遍历位置的下标,不适合这类跨数组位置匹配的场景,直接用普通for循环控制下标遍历即可。


3个数组的基础实现

首先要先校验所有参与遍历的数组长度一致,避免出现数组下标越界异常,代码示例:

public class IndexGroupDemo {
    public static void main(String[] args) {
        // 对应题目中的三个数组
        String[] a = {"a1", "b1", "c1"};
        String[] b = {"a2", "b2", "c2"};
        String[] c = {"a3", "b3", "c3"};

        // 长度合法性校验
        if (a.length != b.length || b.length != c.length) {
            throw new RuntimeException("参与分组的所有数组长度必须保持一致");
        }

        // 按下标遍历,下标从0开始,到数组长度-1结束
        for (int i = 0; i < a.length; i++) {
            // 提取三个数组同位置的元素
            String itemA = a[i];
            String itemB = b[i];
            String itemC = c[i];
            // 按组打印输出
            System.out.printf("第%d组:%s、%s、%s%n", i+1, itemA, itemB, itemC);
        }
    }
}

运行输出结果:

第1组:a1、a2、a3
第2组:b1、b2、b3
第3组:c1、c2、c3

3个以上数组的通用实现

如果数组数量不固定(比如4个、5个甚至更多),可以把所有待处理的数组装入二维数组统一管理,不用硬编码每个数组的取值逻辑,后续新增数组只需要往集合里加即可,代码示例:

public class MultiArrayGroupDemo {
    public static void main(String[] args) {
        String[] a = {"a1", "b1", "c1"};
        String[] b = {"a2", "b2", "c2"};
        String[] c = {"a3", "b3", "c3"};
        String[] d = {"a4", "b4", "c4"}; // 示例新增的第四个数组

        // 所有待分组的数组统一放入二维数组
        String[][] allArrays = {a, b, c, d};

        // 统一做长度校验
        int groupCount = allArrays[0].length;
        for (String[] arr : allArrays) {
            if (arr.length != groupCount) {
                throw new RuntimeException("参与分组的所有数组长度必须保持一致");
            }
        }

        // 按下标分组遍历
        for (int i = 0; i < groupCount; i++) {
            System.out.printf("第%d组:", i+1);
            // 依次取出每个数组当前下标的元素
            for (int arrIndex = 0; arrIndex < allArrays.length; arrIndex++) {
                System.out.print(allArrays[arrIndex][i]);
                if (arrIndex != allArrays.length - 1) {
                    System.out.print("、");
                }
            }
            System.out.println();
        }
    }
}

注意事项

  • 数组是有序的线性存储结构,下标从0开始计数,按下标遍历是这类同位置匹配场景最高效、最简单的实现方式
  • 遍历前的长度校验不能省略,只要有一个数组长度和其他数组不匹配,遍历到超出长度的下标时就会抛出ArrayIndexOutOfBoundsException运行时异常

内容的提问来源于stack exchange,提问作者taeq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 18:39:28