英文:
If hashmap only contains one key, is there a way to get that key without knowing anything about it?
问题
我有一个只有一个键(和一个值)的哈希表。假设我不知道那个键或键的值。有没有办法找到它?这可能听起来很愚蠢,但既然只有一个键,那么有没有办法获取那个键。
英文:
I have a hashamp with only one key (and a value). Lets say I don't know the key or value of that one key. Is there a way to find it? This may sound dumb but since there is only ONE key, then would there be a way to get that key.
答案1
得分: 1
对于单个键映射,只需执行以下操作:
Map<String, String> map = Map.of("A", "B");
System.out.println(map.keySet().iterator().next());
输出:
A
对于更多元素的映射,您可以执行以下操作:
您可以通过map.keySet()
获取映射的keySet()
并遍历它。
如果您想尝试找到与value
关联的特定键,可以通过获取映射的entrySet()
,然后执行以下操作:
String targetVal = "some value";
for (Entry<String, String> e : map.entrySet()) {
if (e.getValue().equals(targetVal)) {
System.out.println(e.getKey());
// 或者
System.out.println(e);
// 继续迭代,因为多个键可以映射到相同的值。
}
}
英文:
For a single key map just do the following:<br>
Map<String,String> map = Map.of("A","B");
System.out.println(map.keySet().iterator().next());
prints
A
For a more populated map you can do the following:
You can get the keySet()
of the map via map.keySet()
and iterate thru that.
If you want to try and find a particular key associated with a value
you can
get the entrySet()
of the map and do something like this:
String targetVal = "some value";
for (Entry<String,String> e : map.entrySet()) {
if (e.getValue().equals(targetVal)) {
System.out.println(e.getKey());
// or
System.out.println(e);
// keep iterating since multiple keys can
// map to the same value.
}
}
答案2
得分: 0
你可以使用 hash_map.keySet()
获取你所有的键。
链接:https://www.geeksforgeeks.org/hashmap-keyset-method-in-java/
英文:
You can get all of your keys with hash_map.keySet()
https://www.geeksforgeeks.org/hashmap-keyset-method-in-java/
答案3
得分: 0
是的,您可以使用iterator
,它使您能够在任何Collection
(或Map
的entrySet()
)上进行迭代:
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("First", "Entry");
System.out.println(map.entrySet().iterator().next());
}
}
这将打印出:First=Entry
,其中First
是键,Entry
是值。
英文:
Yes, you can use iterator
s, which enable you to iterate over any Collection
(or Map
's entrySet()
):
public class Main {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("First", "Entry");
System.out.println(map.entrySet().iterator().next());
}
}
This prints: First=Entry
, where First
is the key and Entry
is the value.
答案4
得分: 0
hashMapObj.entrySet().iterator().next();
是你问题的答案。
英文:
hashMapObj.entrySet().iterator().next();
is the answer to your question.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论