Reputation: 163
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
Reputation: 93842
If you are using java-8, 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:
Stream
of all the entries of your mapSet
Upvotes: 1
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
Reputation: 136022
try this
playersInArenas.values().retainAll(Collections.singleton(5));
Set<String> strings = playersInArenas.keySet();
Upvotes: 1
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