简体   繁体   中英

How to find the lowest value in a hashmap?

I am unable to find the lowest value in a hashmap. There is only one hashmap and in it the lowest value of players must be found.

                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();
                        }
                    }
                }

The output should assign the lowest value among Players into attackerFound variable.

Simply use a stream() with min() to get the lowest value

lowestTrump.values().stream().min(Integer::compareTo);

if the lowestTrump can be null you can also wrap lowestTrump.values() with apache CollectionUtils.emptyIfNull()) or use some another null-safe approach

You can get the minimum player in a single step like this:

Player lowestPlayer = lowestTrump.entrySet()
        .stream()
        .min(Comparator.comparingInt(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .orElse(null);

String attackerFound = lowestPlayer != null ? lowestPlayer.getName() : null;

Be aware that if lowestTrump was empty then attackerFound will be null .

You can use treemap. So that when you add any value to that map, It will already be sorted. You can get first value and that will be the lowest or wise Versa.

Map <Player, Integer> playerMap = new TreeMap<Player, Integer>();

For Java 8+ you can use below example :

playerMap.values().stream().min(Integer::compareTo);

That's it.

Here is my actual working code

                Optional<Player> result = lowestTrump.entrySet()
                        .stream()
                        .filter(c -> c.getValue() != -1)
                        .min(Comparator.comparingInt(Map.Entry::getValue))
                        .map(Map.Entry::getKey);

                if(result != null && result.get().getSuitInHand() != -1) {
                    System.out.println("Player : " + result.get().getName() + " is the first attacker");
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM