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

如何在Java中打印两个ArrayList对应项的最大值及关联名称?

解决方案

你需要通过最大值在scores列表中的索引,匹配students列表里对应的名称,具体实现步骤如下:

  1. 拿到scores的最大值后,调用scores.indexOf(max)获取该值的索引位置
  2. 用这个索引从students列表中取出对应名字
  3. 拼接名字和最大值输出

修改后的完整代码:

import java.util.ArrayList;
import java.util.Collections;

public class Names {
    public static void main(String args[]){

        ArrayList<String> 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<Integer> scores = new ArrayList<>();
        scores.add(100);
        scores.add(250);
        scores.add(120);
        scores.add(300);
        scores.add(200);

        Integer max = Collections.max(scores);
        // 获取最大值的索引
        int maxIndex = scores.indexOf(max);
        // 通过索引获取对应名称
        String topStudent = students.get(maxIndex);
        // 输出结果
        System.out.println(topStudent + " " + max); 
    }
}

补充说明

  • scores.indexOf(max)会返回最大值在scores列表中第一次出现的索引,你的示例中最大值唯一,所以可以直接使用
  • 如果存在多个相同的最大值,这个方法只会返回第一个匹配项的索引,若需要处理多值情况,可以遍历列表收集所有对应索引再做处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 19:35:22