简体   繁体   中英

Iterating Keys, Values of HashMap 4 at a time

I have a 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.

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

//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:

//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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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