我有一个hashmap。
public HashMap<String, Integer> lines = new HashMap<String, Integer>();
我希望返回前4个键,然后是前4个值并重复直到没有任何内容。
如何做到最好?
我整个上午一直在努力:)
答案 0 :(得分:3)
如果您可以设法将所有键作为列表获取,那么您可以一次迭代4个,因为这样您就可以通过索引位置获取它们,就像这样
//get all keys as list
List<String> list = new ArrayList<String>(lines.keySet());
//one iteration of this loop deals with 4 keys and 4 values.
for(i=0; i<n; i=i+4) {
k1 = list.get(i);
v1 = lines.get(k1);
k2 = list.get(i+1);
v2 = lines.get(k2);
k3 = list.get(i+2);
v3 = lines.get(k3);
k4 = list.get(i+3);
v4 = lines.get(k4);
}
修改
如果元素的数量不是4的倍数,那么你可以这样做:
//get all keys as list
List<String> list = new ArrayList<String>(lines.keySet());
//one iteration of this loop deals with 4 keys and 4 values.
int mod = n%4;
for(i=0; i<n-mod; i=i+4) {
k1 = list.get(i);
v1 = lines.get(k1);
k2 = list.get(i+1);
v2 = lines.get(k2);
k3 = list.get(i+2);
v3 = lines.get(k3);
k4 = list.get(i+3);
v4 = lines.get(k4);
}
//deal with last 1, 2 or 3 elements separately.
if(mod>=1) {
k1 = list.get(i);
v1 = lines.get(k1);
if(mod>=2) {
k2 = list.get(i+1);
v2 = lines.get(k2);
if(mod>=3) {
k3 = list.get(i+2);
v3 = lines.get(k3);
}
}
}