1

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

J. Walsh
  • 43
  • 1
  • 4
  • 2
    Can you please post what have you tried and what exactly you want to achieve ? – user3145373 ツ Mar 07 '17 at 11:38
  • I'm no java expert so let me try my best! I am storing a filepath to an image and an integer in the hashmap and writing them to a PDF. But due to formatting of the PDF i need to write the four images first, followed by 4 integers (so they are on the next line of the PDF under the image). – J. Walsh Mar 07 '17 at 11:39
  • what to mean by first 4 keys and first 4 value ! where you want to return ? – user3145373 ツ Mar 07 '17 at 11:41
  • Possible duplicate: http://stackoverflow.com/questions/46898/how-to-efficiently-iterate-over-each-entry-in-a-map?noredirect=1&lq=1 – Shadov Mar 07 '17 at 11:42

1 Answers1

3

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);
        }
    }
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • This is brilliant (and works)! However, if I don't know the size of the list (it could be anything from 1-43) is there a way to take this into consideration? – J. Walsh Mar 07 '17 at 11:55
  • @J.Walsh you can first iterate upto highest multiple of 4, then deal with last few elements separately. See the edited answer. – Raman Sahasi Mar 07 '17 at 12:03
  • Thank you very much! this is perfect! – J. Walsh Mar 07 '17 at 12:56