1

I have two arrays

1) String[] images = {"#1","#2", "#3", "#4", "#5" };

2) String[] items = {"1","2", "3", "4", "5", "6", "7", "8" };

The Items may vary , but the images array is fixed. I wan the output mapping like

 image 1 => item 1
 image 2 => item 2 
 image 3 => item 3
 image 4 => item 4
 image 5 => item 5
 image 1 => item 6
 image 2 => item 7
 image 3 => item 8

and so on. My work around is as follows,

public static void main(String[] args) {
            for( int y=0;y< items.length;y++ ){
            for( int i=0;i< images.length;i++ ){

                if( y >= images.length ){
                    int remaining = items.length % images.length;
                    System.out.println("remaining..." + remaining);
                    for( int x=0;x<=remaining;x++ ){
                        System.out.println( "image" +images[x]+"=> item =>"+items[x]);
                    }
                    return;
                }
                System.out.println( "image" +images[y]+"=> item =>"+items[y]);
                break;
            }
        }
    }
3
  • You haven't tried anything. Loop over the longer array, and use the modulo (%) operator to generate the leftside index.
    – keyser
    Commented Jul 31, 2014 at 5:46
  • image 1,2,3 are mapped to more than one elements, that basically stops you from using a map implementation.
    – AurA
    Commented Jul 31, 2014 at 5:46
  • I tried it but nothing worked. I'll paste my work around.
    – ARP
    Commented Jul 31, 2014 at 5:46

1 Answer 1

6

Try this code:

for (int i=0 ; i<items.length ; i++) {
    System.out.println(images[i%images.length] + " => " + items[i]);
}

i%images.length gives the rest of the division of i, i.e. your position in the items array, with the length of the images array. So images[i%images.length] loops through the images array.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.