我有一张地图:
public static Map<String, Integer> playersInArenas = new HashMap<String, Integer>();
如何搜索Integer(右列)例如5的所有字符串(在左栏中)?
答案 0 :(得分:3)
您可以使用循环并比较每次迭代的值:
// 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());
}
}
注意:而不是打印键,您可以存储它,或者随意做任何事情。
答案 1 :(得分:1)
试试这个
playersInArenas.values().retainAll(Collections.singleton(5));
Set<String> strings = playersInArenas.keySet();
答案 2 :(得分:1)
如果您使用的是java-8,则还可以使用全新的Stream
API。
Set<String> set = playersInArenas.entrySet()
.stream()
.filter(e -> e.getValue() == 5)
.map(e -> e.getKey())
.collect(Collectors.toSet());
它的作用是:
Stream
Set
答案 3 :(得分:0)
您可以使用a遍历迭代地图键集的每个循环:
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);
}