简体   繁体   中英

Java array loop iteration

I have a function of type: I can iterate the array as follows. (Standard example) arrays can be looped over and the elements returned to a variable x as follows.

public Map<String, String> (Object ... args)
{
   . . .
   for( Object x : args); // do stuff
   . . .
   dummyUsexAndPrint(x); // just demonstrating that we can now use x
                         // x will vary on each loop iteration.
}

My objective is to make key value pairs out of the array while not doing any arithmetic. Can we iterate over a loop "two by two"? Something like this ---->

public Map<String, String> (Object ... args)
{
    . . .
    for( Object X : args, Object Y : args) {
        globalMap.put(X,Y); // using X and Y now, instead of just "x"         

                            //in the previous case
    }
    . . .
}

The first case matches the pattern (a_1, a_2 ...). While, I need to match the pattern (a_1, a_2, a_3 ...) and extract a_1 and a_2 on each run of the loop.

Is this kind of pattern matching possible in Java? I have not come across any such examples, Just wish to verify.

Edit:

Suppose we have an array [1,2,3,4,5,6].

A simple loop like

for (int x : array) { ...}

will give me x as 1 2 3 4 5 6

What I want is get 2 values at a time.

for (int x,y : array) { ... }

1 2

3 4

5 6

where the left hand value is x and the right hand value is y.

Edit 2:

for (int i = 0 ; i == array.length - 1; i += 2)
{
x = array[i];
y = array[i + 1];
print(x, y);
}

Does this clear up?

Edit: Seems like there is no way to escape the arithmetic. I was hoping that my array iteration could be done without doing the arithmetic, and it would throw me an exception (so that I do not have to check for even/odds).

The contract would have been for the loop to pick 2 members at a time and loop over. If there were no members left, the contract was fulfilled, if there was one member left, the contract of decomposing two values at a time is violated and an exception thrown.

No such luck, in some languages it is possible to match patterns directly, instead of writing primitive loops. I'm new to Java, so was exploring.

Both of these answers assume that the length of the collection is even (because, obviously, if it isn't, then you won't always have a y for each x ).

For T[] args :

for (int i = 0; i < args.length; i+=2) {
    T x = args[i];
    T y = args[i+1];

    // ... use x and y, e.g. System.out.println(x + " " + y);
}

For a general collection of T s:

boolean even = true;
T x = null;
for (T obj : args) {
    if (even) {
        x = obj;
    } else {
        T y = obj;

        // use x and y, e.g. System.out.println(x + " " + y);
    }
    even ^= true; // flip even
}

This what you looking for:

for (int i = 0; i < args.length - 1; )
{
    int x = args[i];
    int y = args[++i];

    i++;

    System.out.println(x + " " + y);
}

Try using a Deque like this..

 import java.util.*;

 Deque<String> queue = new LinkedList<>(Arrays.asList(new String[] { "1", "2", "3", "4" }));
 Map<String, String> data = new HashMap<>();
 for (int i = 0; i < queue.size(); i++)
    data.put(queue.pop(), queue.pop());

Or you can use an iterator like this in place of a for loop

while (queue.iterator().hasNext()) {
    data.put(queue.pop(), queue.pop());
}

And you have your map with data as you'd wanted. Let me know if that helps

Regards Douglas

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