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

如何基于最高分及后续分数比较两个List<Person>列表?

实现思路与代码示例

核心步骤

  • 提取两个列表中所有Person的score值,按降序排序
  • 从第一个元素开始逐个位置比较分数:
    • 若某一位置分数不同,直接返回分数更高的列表胜出
    • 若对应位置分数全部相同,则比较列表长度:更长的列表胜出;长度相同则判定为平局

Java代码实现

假设Person类定义如下:

class Person {
    private int score;
    // 构造方法与getter
    public Person(int score) {
        this.score = score;
    }
    public int getScore() {
        return score;
    }
}

比较逻辑的工具方法:

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ListScoreComparator {
    // 返回结果:1=list1胜出,-1=list2胜出,0=平局
    public static int comparePersonLists(List<Person> list1, List<Person> list2) {
        // 提取分数并降序排序
        List<Integer> sortedScores1 = list1.stream()
                .map(Person::getScore)
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());
        List<Integer> sortedScores2 = list2.stream()
                .map(Person::getScore)
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());
        
        // 按最小长度遍历比较
        int minLength = Math.min(sortedScores1.size(), sortedScores2.size());
        for (int i = 0; i < minLength; i++) {
            int score1 = sortedScores1.get(i);
            int score2 = sortedScores2.get(i);
            if (score1 > score2) {
                return 1;
            } else if (score1 < score2) {
                return -1;
            }
            // 分数相同则继续下一轮比较
        }
        
        // 前面分数全相同,比较列表长度
        return Integer.compare(sortedScores1.size(), sortedScores2.size());
    }

    // 测试示例
    public static void main(String[] args) {
        List<Person> list1 = List.of(new Person(3), new Person(5), new Person(8));
        List<Person> list2 = List.of(new Person(8), new Person(4), new Person(7));
        
        int result = comparePersonLists(list1, list2);
        if (result == 1) {
            System.out.println("list1胜出");
        } else if (result == -1) {
            System.out.println("list2胜出");
        } else {
            System.out.println("两个列表分数完全一致");
        }
        // 示例排序后list1分数为[8,5,3],list2为[8,7,4],第二个位置5<7,最终输出list2胜出
    }
}

关键细节说明

  • 必须使用降序排序,确保比较顺序是从最高分到次高分
  • 当对应位置分数全相同时,默认更长的列表胜出(若需调整平局规则,可修改最后返回值的逻辑)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:24:21