如何在Java中通过Map进行迭代? [英] How to iterate through a Map in java?
问题描述
我需要遍历BucketMap
并获取所有keys
,但是例如如何在不尝试手动操作的情况下到达buckets[i].next.next.next.key
之类的东西,就像我在这里尝试的那样:
I need to iterate through a BucketMap
and get all keys
but how do I get to something like buckets[i].next.next.next.key
for instance without doing it manually as I tried here:
public String[] getAllKeys() {
int j = 0; //index of string array "allkeys"
String allkeys[] = new String[8];
for(int i = 0; i < buckets.length; i++) { //iterates through the bucketmap
if(buckets[i] != null) { //checks wether bucket has a key and value
allkeys[j] = buckets[i].key; //adds key to allkeys
j++; // counts up the allkeys index after adding key
if(buckets[i].next != null) { //checks wether next has a key and value
allkeys[j] = buckets[i].next.key; //adds key to allkeys
j++;
}
}
}
return allkeys;
}
我还如何使用迭代完成后得到的j
版本初始化String[] allkeys
作为索引?
Also how can I initialize the String[] allkeys
using the version of j
we get after the iteration is done as the index?
推荐答案
对于基本的使用,HashMap是最好的,我已经介绍了如何对其进行迭代,比使用迭代器更容易:
For basic utilisation, the HashMap is the best, I've put how to iterate over it, easier than using an iterator :
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
}
意思是:对于映射键中的所有字符串,我们都会做一些事情,并且在每次迭代时,我们都会将键称为名称"(它可以是您想要的任何东西,它是一个变量)
means : "For all string from the keys of the map, we'll do something, and at each iteration we will call the key 'name' (it can be whatever you want, it's a variable)
我们在这里:
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中通过Map进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!