如何同时获取两个 ArrayList 中最大值及其对应元素

本文介绍如何在 java 中根据一个 arraylist 的最大值,精准定位并打印另一个 arraylist 中与之索引对应的元素(如人名与最高分匹配),避免仅输出最大值或全部列表的常见错误。

要实现“打印最高分(300)及其对应姓名(Abraham Lincoln)”,关键在于获取最大值所在的索引位置,而非仅获取最大值本身。Collections.max(scores) 只返回值(如 300),不提供其在列表中的位置;而我们需要的是该值的下标(这里是 3),才能从 students 列表中取出 students.get(3)。

以下是推荐的解决方案——通过遍历 scores 找到最大值索引:

import java.util.ArrayList;
import java.util.List;

public class Names {
    public static void main(String[] args) {
        ArrayList students = new ArrayList<>();
        students.add("John F. Kennedy");
        students.add("Donald Trump");
        students.add("Theodore Roosevelt");
        students.add("Abraham Lincoln");
        students.add("Millard Fillmore");

        ArrayList scores = new ArrayList<>();
        scores.add(100);
        scores.add(250);
        scores.add(120);
        scores.add(300);
        scores.add(200);

        // 查找 scores 中最大值的索引
        int maxIndex = 0;
        for (int i = 1; i < scores.size(); i++) {
            if (scores.get(i) > scores.get(maxIndex)) {
                maxIndex = i;
            }
        }

        // 使用同一索引获取对应学生姓名和分数
        String topStudent = students.get(maxIndex);
        int topScore = scores.get(maxInd

ex); System.out.println(topStudent + " " + topScore); // 输出:Abraham Lincoln 300 } }

优势说明

  • 时间复杂度为 O(n),仅一次遍历,高效且易理解;
  • 索引严格对齐,天然保证两个列表的逻辑关联性(前提是两列表长度相等、顺序一一对应);
  • 无需额外依赖(如 Collections.max + 二次查找索引),避免重复遍历或潜在的重复值歧义(如多个 300 时,默认取第一个出现位置)。

⚠️ 注意事项

  • 务必确保 students 和 scores 长度一致,且元素顺序语义匹配(即 students.get(i) 确实对应 scores.get(i));
  • 若列表可能为空,应在查找前添加非空校验(例如 if (scores.isEmpty()) throw new IllegalStateException("Scores list is empty"););
  • 如需处理多个并列最高分并全部输出,可改用 List 存储所有 maxIndex,再批量打印。

掌握“以索引为桥梁联动双列表”的思路,是处理 Java 中平行数据结构(如姓名-成绩、商品-价格、ID-状态等)的基础能力,也是避免硬编码或错误映射的关键实践。