如何找到哈希图中的最低值?

我无法找到哈希图中的最低值。只有一个哈希图,必须在其中找到玩家的最低值。


                for (Map.Entry<Player, Integer> entry1 : lowestTrump.entrySet()) {

                    Player key1 = entry1.getKey();

                    int value1 = entry1.getValue();


                    for (Map.Entry<Player, Integer> entry2 : lowestTrump.entrySet()) {

                        Player key2 = entry2.getKey();

                        int value2 = entry2.getValue();


                        if(value1 == -1 || value2 == -1){

                            break;

                        }else if(value1 < value2 && (value1 != 1 || value2 != 1)) {

                            attackerFound = key1.getName();

                        }

                    }

                }

输出应将玩家中的最低值分配给attackerFound 变量。


猛跑小猪
浏览 150回答 4
4回答

至尊宝的传说

只需使用stream()withmin()即可获得最低值lowestTrump.values().stream().min(Integer::compareTo);如果lowestTrump可以为空,您也可以lowestTrump.values()用 apache包装CollectionUtils.emptyIfNull())或使用另一种空安全方法

白猪掌柜的

您可以像这样一步获得最小玩家:Player lowestPlayer = lowestTrump.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; .min(Comparator.comparingInt(Map.Entry::getValue))&nbsp; &nbsp; &nbsp; &nbsp; .map(Map.Entry::getKey)&nbsp; &nbsp; &nbsp; &nbsp; .orElse(null);String attackerFound = lowestPlayer != null ? lowestPlayer.getName() : null;请注意,如果lowestTrump为空,则将attackerFound为null。

有只小跳蛙

这是我的实际工作代码&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Optional<Player> result = lowestTrump.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(c -> c.getValue() != -1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .min(Comparator.comparingInt(Map.Entry::getValue))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(Map.Entry::getKey);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(result != null && result.get().getSuitInHand() != -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Player : " + result.get().getName() + " is the first attacker");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }

慕沐林林

您可以使用树状图。这样,当您向该映射添加任何值时,它就已经被排序了。您可以获得第一个值,这将是最低或明智的 Versa。Map&nbsp;<Player,&nbsp;Integer>&nbsp;playerMap&nbsp;=&nbsp;new&nbsp;TreeMap<Player,&nbsp;Integer>();对于 Java 8+,您可以使用以下示例:playerMap.values().stream().min(Integer::compareTo);就是这样。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java