Iterating over multidimension array

Hi,
I'm iterating over multidimentional array using ForEach statement. Let say the array is a 4D array and looks like:
AnArray[0..4][0..3][0..2][0..1]
I want o execute somenthing for every element of this array. To do this I'm using - as I've mentioned - ForEach loop. The point is that the order of the element iterating over is different from the order I expected.
The iteration process starts from iterating first element of first dimention (defined on most lest side - in my example [0..4]). My expectation was that the iteration starts by changing elemnts in dimension defined on most right side - in the example above dimension [0..1].
Is there any chance to change the iteration order?
Thanks.

I do not think there is a way to change the order with foreach, however you can always use your own nested loops and loop iteration variables to iterate in any order you like. For example:
for (int i = 0; i <= 4; i++)
    for(int j = 0; j <= 3; j++)
        for(int k = 0; k <= 2; k++)
            for(int l = 0; l <= 2; l++)
                AnArray[i][j][k][l]
Another alternative is to change the order of the indices you are using for your array to be the way that will make foreach work out the way you want it to.
Or you might consider posting to the Idea Exchange to propose adding a setting to foreach for this (or something similar): http://forums.ni.com/t5/NI-TestStand-Idea-Exchange/idb-p/teststandideas
Hope this helps,
-Doug

Similar Messages

  • Iterating over an array without the datatable

    I would like repeat a portion of code for each element in any array of a backing bean. However I do not want the cells that the dataTable tag provides. What are my other options to iterate over an array?

    create your own component, or just another renderer for uidata. it's rather easy task.

  • Two unexpected Locals variables when iterating over array of containers​.

    Hi,
    I iterate over an array of containers. In the ForEach loop step variables format I have defined two variables; one is current offset, second one is current element.
    The loop works fine.
    However, during the debug process, I've spotted two new Locals variables called __ElementSibling0 (type: number) and __ForEachReleaser0 (type: obj. reference) created silently by TS as soon as I start iterating over my array. What are they?
    Do they exist because:
    I'm iterating over an array of containers, or
    I use  the _currentElement_Freq variable, or
    it always like that?
    Solved!
    Go to Solution.

    Those are used by the implementation of the For Each step. You can see them only because you have enabled the Show Hidden Properties setting.
    You can safely ignore their presence.

  • OSB - Iterating over large XML files with content streaming

    Hi @ll
    I have to iterate over all item in large XML files and insert into a oracle database.
    The file is about 200 MB and contains around 500'000, and I am using OSB 10gR3.
    The XML structure is something like this:
    <allItems>
    <item>.....</item>
    <item>.....</item>
    <item>.....</item>
    <item>.....</item>
    <item>.....</item>
    </allItems>
    Actually I thought about using a proxy service with enabled content streaming and a "for each" action for iterating
    over all items. But for this the whole XML structure has to be materialized into a variable otherwise it is not possible!
    More about streaming large files can be found here:
    [http://download.oracle.com/docs/cd/E13159_01/osb/docs10gr3/userguide/context.html#large_messages]
    There is written "When you enable streaming for large message processing, you cannot use the ... for each...".
    And for accessing single items you should should use an assign action with a xpath like "$body/allItems/item[1]";
    this works fine and not the whole XML stream has to be materialized.
    So my idea was to use the "for each" action and processing seqeuntially all items with a xpath like:
    $body/allItems/item[$counter]
    But the "for each" action just allows iterating over a sequence of xml items by defining an selection xpath
    and the variable that contains all items. I would like to have a "repeat until" construct that iterates as long
    $body/allItems/item[$counter] returns not null. Or can I use the "for each" action differently?
    Does the OSB provides any other iterating mechanism? I know there is this spli-join construct that supports
    different looping techniques, but as far I know it does not support content streaming, is this correct?
    Did I miss somehting?
    Thanks a lot for helping!
    Cheers
    Dani
    Edited by: user10095731 on 29.07.2009 06:41

    Hi Dani,
    Yes, according to me this would be the best approach. You can use content-streaming to pass this large xml to ejb and once it passes successfully EJB should operate on this. If you want any result back (for further routing), you can get it back from EJB.
    EJB gives you power of java to process this file and from java perspective 150 MB is not a very LARGE data. Ensure that you are using buffering. Check out this link for an explanation on Java IO Streams and, in particular, buffered streams -
    http://java.sun.com/developer/technicalArticles/Streams/ProgIOStreams/
    Try dom4J with xpp (XML Pull Parser) parser in case you have parsing requirement. We had worked with 1.2GB file using this technique.
    Regards,
    Anuj

  • Looping over an array avoiding scriptlets

    Hello,
    I want to loop over an array avoiding java scriptlets. Here is the code I would like to "clean".
    <%
    int rowCol=0;
    for(int i=0; i<countryArray.length; i++){
    rowCol++;
    Country country = (Country)countryArray;
    out.println("<tr " + ((rowCol%2==0)?("class=\"evenRow\""):("class=\"oddRow\"")) + ">");
    out.println("<td class=\"countryName\">" country.getName() "</td>");
    out.println("<td class=\"countryCapital\">" country.getCapital() "</td>");
    out.println("<td class=\"number\">" + country.getFormattedLandArea() + "</td>");
    out.println("<td class=\"number\">" country.getFormattedPopulation() "</td>");
    out.println("<td class=\"number\">" country.getFormattedGdp() "</td>");
    out.println("<td class=\"number\">" country.getFormattedGdp_per_head() "</td>");
    out.println("<td><a class=\"more\" href=\"pais.jsp?countryID=" + country.getId() + "\">m?s...</a></td>");
    out.println("</tr>");
    %>
    Can anyone give me some guidelines please?
    Thanks in advance,
    Julien.

    you mean this:
    <%
    int rowCol=0;
    for(int i=0; i<countryArray.length; i++){
      rowCol++;
      Country country = (Country)countryArray;
    %>
    <tr class="<%= rowCol%2==0? "evenRow" : "oddRow" %>">
    <td class="countryName"><%= country.getName() %></td>
    <td class="countryCapital"><%= country.getCapital() %></td>
    <td class="number"><%= country.getFormattedLandArea() %></td>
    <td class="number"><%= country.getFormattedPopulation() %></td>
    <td class="number"><%= country.getFormattedGdp() %></td>
    <td class="number"><%= country.getFormattedGdp_per_head() %></td>
    <td><a class="more" href="pais.jsp?countryID=<%= country.getId() %>">m?s...</a></td>
    </tr>
    <%
    %>

  • [SOLVED] Iteration over a BPM Object.

    Hi guys, here i'm trying to solve a problem. May be simple, but i cant iterate over a BPM object without using the fuego taglibs.
    I need to iterate over the object X. The X object have one attribute, called itens, that is a group with values.
    In my JSP, using the code, works:
    <tr><td><b>Objeto.codigo:</b></td><td><f:fieldValue att="x.code" onlyValue="true"/></td></tr>
    <tr><td><b>Objeto.nome:</b></td><td><f:fieldValue att="x.name" onlyValue="true"/></td></tr>
    <tr><td><b>Objeto.item1:</b></td><td><f:fieldValue att="x.itens[0].description" onlyValue="true"/></td></tr>
    I have tried a conjuction with a <c:forEach> to iterate over the x.itens attribute without success, like this
    <c:forEach var="item" items="${x.itens}">
    ${item.description}
    </c:forEach>
    With JSP EL, there's a way to access this attribute without workarounds?
    Thanks!
    Thiago
    Edited by: user10128107 on 08/01/2009 04:04
    It was the use of the core taglib...
    Edited by: user10128107 on 08/01/2009 05:49

    madeqx wrote:
    Will this piece of code be significantly slower than iteration over an ArrayList?a) No. Iteration is O(n) in both cases.
    b) Irrelevant. If your design calls for a map, use a map, and if it calls for a list, use a list. The two serve entirely different purposes, and we don't choose between map and list for performance reasons.

  • Dynamic iterating over table columns

    hello there,
    i have to create a string depending on the values in my table columns. this string creation is used on different tables with different number of columns and different column types.
    so i want to write a procedure which does simplified the following:
    1. create dynamic rowtype with a select statement
    2. iterate over rowtype columns and append column value to a string
    3. insert the created string in another table.
    by trying this dynamically for any table i run in the following two issues:
    1. creation of a rowtype needs the tabletype
    2. no iterating over rowtype possible
    are their any ideas to solve this issue. or do i have to write a procedure for every table i use.
    regards,
    rené

    You can do it with a single, generic procedure using DBMS_SQL.
    Joe Fuda
    SQL Snippets

  • Any performance overhead if we get iterator over values stored in map

    Hi Everybody,
    Is there any performance overhead if we get iterator over values stored in map. like this
    Iterator itr = rolesMap.values().iterator();
    if yes please explain...thanks in advance.

    ejp wrote:
    That's rather out of date. It is how Hashtable works, but as regards HashMap it isn't. The keySet() iterator and the values() iterator are both written in terms of the entrySet() iterator. There is no skipping over unused slots.Out of date? In that case there's been a recent advance in hashed data structures I've missed.
    Or the HashMap implementation has been recently changed to internally link entries to improve iteration performance. I doubt that because such a list would degrade the performance of the HashMap in other ways and that's unacceptable (and unnecessary because of LinkedHashMap).
    Besides, what I said is in the Java 6 API documentation to LinkedHashMap. It may be out of date but I doubt it.
    So here we are with a fact of nature: Any iteration of a hash based data structure will be proportional to capacity rather than the number of entries, unless a supportive list style data structure is introduced to overcome this.

  • Iterating over the Values returned from a HashMap

    Hi,
    I have a HashMap which stores some Strings as Keys and their corresponding Values are a Vector of Strings.
    for eg. one (Key, Value) pair is
    (String1, [StringA, StringB, StringC, ........])
    I understand that I can read the Vector Values by iterating over the HashMap using the ".entrySet()" and "Map.Entry" operations.
    My problem is I am not able to iterate through the Vector values returned by the ".getValue( )" method.
    can anyone please give some hints as to where I am commiting an error, or if I need to cast my values in some manner to iterate over them?
    thanks in advance

    can anyone please give some hints as to where I am commiting an errorSomewhere in your code. Post the smallest complete example which demonstrates the problem, then people may be able to give more specific help.

  • Capture when finished iterating over query results...

    Hello. I have a flex app that queries a web service. The code
    to iterate over the results is shown below. the query string is
    passed to the connection, and the results are processed inline.
    I want to know when i'm done iterating over the results. How
    do i do this? My current approach seems clumsy. I add an event
    listener to my connection for query complete. When that fires, I
    get the length of the result set. Then in my iterator, i have a
    condition that checks when the record count is equal to the length
    of the result set. i assume there's an easier/better way?
    queryResultIterator2 = new QueryResultIterator(wsconn,
    queryString,
    function (so:SObject):Boolean {
    productCodeAC.addItem(so.Product_Code__c);
    return true;
    thanks
    chris

    Hi Dan
    When i use the cfouput with the group attribute... the query only returns one of the columns from the table for stock spool sizes...
    so the new query results will have 1 part which is good 10 Sol | 31.43 | 1000
    but only 1000 .. when it should return 1000 | 2500 | 5000  based on that wireid
    Thanks

  • Getting a iterator over a huge xml-file

    Hi !
    I have to persist data from some huge xml-files.
    The structure of the xml is simple, like in:
    <items>
    <item>
    </item>
    <item>
    </item>
    </items>
    The best way for me, is to get an iterator over the item-elements represented as a DOM strcture for easy access.
    Because the files are so huge (80-150 MBytes) and I have no control over the creation of them, the underlying parser should be SAX oriented.
    So I need a solution which will parse until one item-element (maybe spezified through a XPATH query) is completed and build a DOM-tree from it.
    Then I can pass this DOM-element to my persistence layer. When this item is persisted, and the Iterator hasNext(), then I could do a simple .next() to get the next DOM representation of the item.
    Is there such a solution out ? Or do I have to 'invent' such kind of parsing ?
    Would by great to get some hints ... this problem is driving me crazy :)
    Thank you in advance,
    Gerald

    Vaguely familiar, http://lists.xml.org/archives/xml-dev/200201/msg00032.html
    I can't think of a DOM builder that would work off a fragment; you would probably have to create one yourself.
    There's also http://drizzle.stanford.edu/~peastman/pax.html which might solve your problem.
    Pete

  • Is iteration over a HashMap significantly slower than an ArrayList?

    Will this piece of code be significantly slower than iteration over an ArrayList?
    for(Object o : myMap.values()){
    I'm expecting the map to contain roughly between 10 and 50 elements.
    thanks,

    madeqx wrote:
    Will this piece of code be significantly slower than iteration over an ArrayList?a) No. Iteration is O(n) in both cases.
    b) Irrelevant. If your design calls for a map, use a map, and if it calls for a list, use a list. The two serve entirely different purposes, and we don't choose between map and list for performance reasons.

  • Reposting: Question regarding iteration over synchronized list

    [added proper markup]
    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
         * Create new animals from existing animals
         * @return The cohort of newborn animals
        public List<IAnimal> regenerate() {
            List<IAnimal> children = new ArrayList<IAnimal>();
            synchronized (animalList) {
                Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
                 while (it.hasNext()) {
                     IAnimal a = it.next();
                     if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
                         IAnimal child = a.reproduce();
                         children.add(child);                    // newborns
    //                     animalList.add(child);                    // the whole population  //THROWS CME!
                 animalList.addAll(children);                                     // does not throw CME
            return children;
        }Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
          List<IAnimal> backingList =
                new LinkedList<IAnimal>() {
                     * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
                     * try again.
                     * @param   animal  The animal to be added
                     * @return  true
                    public boolean add(IAnimal animal) {
                        boolean added = false;
    outer:
                        do {
                            // synchronized (this) {                // DIDN'T HELP
                            Iterator<IAnimal> iAnimals = iterator();
                            while (iAnimals.hasNext()) {
                                //FIXME: this algorithm assumes square animals
                                Point existingAnimalLocation = iAnimals.next().getLocation();
                                double distance = existingAnimalLocation.distance(animal.getLocation());
                                if (distance < animal.getSize().getWidth()) {
                                    animal = new Animal();
                                    continue outer;
                            //}  //end unhelpful synchro block
                            super.add(animal);
                            added = true;
                        while (!added);
                        return added;
                    } // end method add
                };

    Jefferino wrote:
    spoon_ wrote:
    By the way that Iterators in Java are designed, you are not allowed to modify a list as you iterate over it.
    Not true: Iterator.remove().
    Edited by: Jefferino on Mar 20, 2008 2:24 AMOh yeah, you can modify it using the iterator's methods; but not using any of the collection's methods, like add().

  • Question regarding iteration over synchronized list

    I've got an A-Life program I work on for fun. I thought I understood (sorta) synchronized collections, but this puzzles me. The method body is as follows:
    * Create new animals from existing animals
    * @return The cohort of newborn animals
    public List<IAnimal> regenerate() {
    List<IAnimal> children = new ArrayList<IAnimal>();
    synchronized (animalList) {
    Iterator<IAnimal> it = animalList.iterator();          // must be in synchro block according to JDK notes
         while (it.hasNext()) {
         IAnimal a = it.next();
         if (a.isPregnant() && ((GeneModel.getInstance().getTicks() % getEnvironment().getAnimal().getReproCycle()) == 0)) {
         IAnimal child = a.reproduce();
         children.add(child);                    // newborns
    //     animalList.add(child);                    // the whole population //THROWS CME!
         animalList.addAll(children); // does not throw CME
    return children;
    Animal list is a synchronized list (backed by and ArrayList). Note that I've synchronized on the list, yet adding children individually throws a ConcurrentModificationException (I did overwrite the add() method on the backing list, but I wouldn't think that would be a problem; it might be in that it iterates over itself... but synchronizing that doesn't help, either).
    Anyhow, doing an addAll outside of the synchronization block works fine (also works if I loop through the children and add them at this point).
    Is it my override of the add() method? From what I can see, the synchronized wrapper just adds a mutex to each access method in the backing list. Here's the method override:
    List<IAnimal> backingList =
    new LinkedList<IAnimal>() {
    * Checks that we're not putting one animal on top of another. If we are, we generate a new animal and
    * try again.
    * @param animal The animal to be added
    * @return true
    public boolean add(IAnimal animal) {
    boolean added = false;
    outer:
    do {
    // synchronized (this) {                // DIDN'T HELP
    Iterator<IAnimal> iAnimals = iterator();
    while (iAnimals.hasNext()) {
    //FIXME: this algorithm assumes square animals
    Point existingAnimalLocation = iAnimals.next().getLocation();
    double distance = existingAnimalLocation.distance(animal.getLocation());
    if (distance < animal.getSize().getWidth()) {
    animal = new Animal();
    continue outer;
    //} //end unhelpful synchro block
    super.add(animal);
    added = true;
    while (!added);
    return added;
    } // end method add
    };

    Your code is not formatted (use code tags for this) but it seems to me that you add elements to the list while you iterate over it, hence a ConcurrentModificationException is thrown. Use a ListIterator if you want to add to the list while iterating.

  • Iterating over strange object

    this must be pretty simple but i can't figure out what to do:
    I have a class defined like this:
    public IndexExample  (String infile){
              Map<String,TreeSet> IndexExample = new TreeMap<String,TreeSet>();
    .IndexExample is not empty now i want to run over the Map, and for each string run on the TreeSet, I though about something like this:
    however the bolded stuff gives me:
    "The method entrySet() is undefined for the type IndexExample"
    what should i do?
    [u]Set s = this.entrySet();[/u]
              Iterator iter1 = s.iterator();
            while (iter1.hasNext()){
                Map.Entry m = (Map.Entry)iter1.next();
                String key = (String)m.getKey();
                TreeSet pages = (TreeSet)m.getValue();
                Iterator iter2 = pages.iterator();
                 }thanks
    Eran

    thank you all
    but what i didn't mention (oopse)
    that the first piece of code is the constructor for the class.
    the second piece of code is some method.
    but it doesn't let me use the method entrySet();
    thanks in advance...
    i put my code again:
    import java.io.*;
    import java.util.*;
    public class IndexExample{
         final static char DELIMITER = ';';
    //constructor:
         public IndexExample  (String infile){
              Map<String,TreeSet> IndexExample = new TreeMap<String,TreeSet>();
               try {
                    BufferedReader in = new BufferedReader(new FileReader(infile));
                     String line;
                     while ((line = in.readLine()) != null) {
                         int delimiterIndex = line.indexOf(DELIMITER);
                         if (delimiterIndex < 0) {
                              continue;
                         String argument1 = line.substring(0,delimiterIndex-1);
                         String argument2 = line.substring(delimiterIndex+1,line.length());
                         String key = (argument1).trim();
                         Integer pageNumber = new Integer(argument2.trim());
                         TreeSet<Integer> pages = new TreeSet();
                         if (IndexExample.containsKey(key)) {
                              pages = IndexExample.get(key);
                         else {
                              pages = new TreeSet();
                         pages.add(pageNumber);
                         IndexExample.put(key,pages);
                     in.close();
                 catch (IOException e) {
    //some method
         public void toFile(String outFile){
              PrintWriter out = new PrintWriter(new FileWriter(outFile));
              Set s = this.entrySet();
              Iterator iter1 = s.iterator();
            while (iter1.hasNext()){
                 Map.Entry m = (Map.Entry)iter1.next();
                String key = (String)m.getKey();
                TreeSet pages = (TreeSet)m.getValue();
                Iterator iter2 = pages.iterator();
                out.print(key + ", ");
                 while (iter2.hasNext()){
                      int i = (Integer)iter2.next();
                      out.print(i + " ");
                 out.println("");
            out.close();
            }

Maybe you are looking for