List of all value values ​​on the map

I have a map:

public static Map<String, Integer> playersInArenas = new HashMap<String, Integer>();

How can I search for all rows (in the left column), where is Integer (right column), for example, 5?

+4
source share
4 answers

You can use a loop and compare the value at each iteration:

// declaring map
Map<String, Integer> playersInArenas = new HashMap<String, Integer>();
playersInArenas.put("A", 5);
playersInArenas.put("B", 4);
playersInArenas.put("C", 5);

// "searching" strings
for (Entry<String, Integer> e : playersInArenas.entrySet()) {
    if (e.getValue() == 5) {
        System.out.println(e.getKey());
    }
}

Note. Instead of typing a key, you can save it or do whatever you want with it.

+3
source

try it

    playersInArenas.values().retainAll(Collections.singleton(5));
    Set<String> strings = playersInArenas.keySet();
+1
source

, Stream API.

Set<String> set = playersInArenas.entrySet()
                                 .stream()
                                 .filter(e -> e.getValue() == 5)
                                 .map(e -> e.getKey())
                                 .collect(Collectors.toSet());

:

  • Stream
  • , , 5
  • Set
+1

You can use for each loop that iterates through a set of map keys:

Map<String, Integer> playersInArenas = new HashMap<String,Integer>();
playersInArenas.put("hello", 5);
playersInArenas.put("Goodbye", 6);
playersInArenas.put("gret", 5);
for(String key : playersInArenas.keySet()){
    //checks to see if the value associated with the current key
    // is equal to five
    if(playersInArenas.get(key) == 5){
        System.out.println(key);            
    }
0
source

Source: https://habr.com/ru/post/1541852/


All Articles