简体   繁体   English

迭代键,一次HashMap 4的值

[英]Iterating Keys, Values of HashMap 4 at a time

I have a hashmap. 我有一个hashmap。

public HashMap<String, Integer> lines = new HashMap<String, Integer>();

and I would like to return the first 4 keys, followed by the first 4 values and repeat until there is nothing left. 我想返回前4个键,然后是前4个值并重复直到没有任何东西。

How best to do this? 怎么做到最好?

I've been trying all morning :) 我整个上午都在尝试:)

If you can manage to get all the keys as a list, then you can iterate them 4 at a time because that way you would be able to get them by index position, something like this 如果您可以设法将所有键作为列表获取,那么您可以一次迭代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);
}

EDIT 编辑

If the number of elements are not multiple of 4, then you can do something like this: 如果元素的数量不是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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM