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

Java中从Map筛选值为最高分的Player列表问题排查

问题分析与解决方案

一、两种实现的错误原因

1. 第一种循环方式返回空列表的原因

你的highestScore是Optional<Integer>类型,而entry.getValue()返回的是Integer类型。使用equals()比较时,是将Integer对象与Optional<Integer>对象做对比,两者类型完全不同,永远不会相等,导致循环内的条件从未触发,最终tiePlayers为空列表。

2. 第二种Stream方式抛出ClassCastException的原因

Stream的filter+map操作后返回的是Stream<Player>对象,它并不是List的子类,直接强制类型转换必然抛出类型转换异常。必须通过collect()方法将Stream流中的元素收集为List集合。

二、正确实现方式

修复后的循环实现

先从Optional中取出实际的最高分(需先判断是否存在,避免空指针),再进行匹配:

// 先检查最高分是否存在
if (highestScore.isPresent()) {
    Integer maxScore = highestScore.get();
    for (Map.Entry<Player, Integer> entry : results.entrySet()) {
        if (entry.getValue().equals(maxScore)) {
            tiePlayers.add(entry.getKey());
        }
    }
}

正确的Stream实现

利用Optional的map方法安全处理最高分,同时通过collect(Collectors.toList())将Stream转为List:

import java.util.stream.Collectors;
import java.util.Collections;

// 若最高分存在则收集匹配的Player,否则返回空列表
tiePlayers = highestScore.map(score -> 
    results.entrySet().stream()
           .filter(entry -> entry.getValue().equals(score))
           .map(Map.Entry::getKey)
           .collect(Collectors.toList())
).orElse(Collections.emptyList());

优化最高分计算(可选)

你当前的最高分计算依赖scoreResultsSorted,可以直接从results集合中获取最大值,更简洁准确:

Optional<Integer> highestScore = results.values().stream()
                                       .max(Integer::compareTo);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:05:50