gpt4 book ai didi

java - 如何在 Java 中遍历 Map?

转载 作者:太空狗 更新时间:2023-10-29 22:31:10 25 4
gpt4 key购买 nike

我需要遍历 BucketMap 并获取所有 keys 但我如何获得类似 buckets[i].next.next.next 的内容。 key 例如我在此处尝试时无需手动执行:

public String[] getAllKeys() {
//index of string array "allkeys"
int j = 0;
String allkeys[] = new String[8];
//iterates through the bucketmap
for (int i = 0; i < buckets.length; i++) {
//checks wether bucket has a key and value
if (buckets[i] != null) {
//adds key to allkeys
allkeys[j] = buckets[i].key;
// counts up the allkeys index after adding key
j++;
//checks wether next has a key and value
if (buckets[i].next != null) {
//adds key to allkeys
allkeys[j] = buckets[i].next.key;
j++;
}
}
}
return allkeys;
}

另外,如何使用迭代完成后获得的 j 版本作为索引来初始化 String[] allkeys

最佳答案

对于基本使用,HashMap 是最好的,我已经介绍了如何迭代它,比使用迭代器更容易:

public static void main (String[] args) {
//a map with key type : String, value type : String
Map<String,String> mp = new HashMap<String,String>();
mp.put("John","Math"); mp.put("Jack","Math"); map.put("Jeff","History");

//3 differents ways to iterate over the map
for (String key : mp.keySet()){
//iterate over keys
System.out.println(key+" "+mp.get(key));
}

for (String value : mp.values()){
//iterate over values
System.out.println(value);
}

for (Entry<String,String> pair : mp.entrySet()){
//iterate over the pairs
System.out.println(pair.getKey()+" "+pair.getValue());
}
}

快速解释:

for (String name : mp.keySet()){
//Do Something
}

意思是:“对于来自 map 键的所有字符串,我们将做一些事情,并且在每次迭代中我们将调用键'name'(它可以是你想要的任何东西,它是一个变量)


开始吧:

public String[] getAllKeys(){ 
int i = 0;
String allkeys[] = new String[buckets.length];
KeyValue val = buckets[i];

//Look at the first one
if(val != null) {
allkeys[i] = val.key;
i++;
}

//Iterate until there is no next
while(val.next != null){
allkeys[i] = val.next.key;
val = val.next;
i++;
}

return allkeys;
}

关于java - 如何在 Java 中遍历 Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43015098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com