Alexander K.
Alexander K.

Reputation: 163

List all occurs of a value in a Map

I have a map:

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

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

Upvotes: 4

Views: 54

Answers (4)

Alexis C.
Alexis C.

Reputation: 93842

If you are using , you could also use the brand new Stream API.

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

What it does is:

  • get a Stream of all the entries of your map
  • apply a filter to only get the entries that have the value 5
  • map each entry to its key
  • collect the result in a Set

Upvotes: 1

Bryan
Bryan

Reputation: 2078

You could use a for each loop that iterates through the maps key set:

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

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136022

try this

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

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

You can use a loop and compare the value on 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 printing the key you could store it, or do whatever you want with it.

Upvotes: 3

Related Questions