Iterate through string array in Java

后端 未结 10 790
逝去的感伤
逝去的感伤 2020-11-30 01:21

I have String array with some components, this array has 5 components and it vary some times. What I would like to do is to iterate through that array and get the first comp

相关标签:
10条回答
  • 2020-11-30 01:59
    String[] elements = { "a", "a", "a", "a" };
    
    for( int i = 0; i < elements.length - 1; i++)
    {
        String element = elements[i];
        String nextElement = elements[i+1];
    }
    

    Note that in this case, elements.length is 4, so you want to iterate from [0,2] to get elements 0,1, 1,2 and 2,3.

    0 讨论(0)
  • 2020-11-30 02:01

    If you are looking for performance and the order of iteration is not relevant, you can iterate using an optimized reverse loop:

    int elemLength = elements.length;
    if(elemLength < 2){
      // avoid ArrayIndexOutOfBoundsException ...
    } else {
      String elem1, elem2;
      for(int i = elemLength -1; --i >= 0;) {
        elem1 = elements[i];
        elem2 = elements[i+1];
        // do whatever you want with those two strings
      }
    }
    

    In such a way you are retrieving the length of the array once, then decrementing the index and comparing with zero in a single operation. Comparing with zero is a very fast operation, often optimized by many architectures (easier / faster than comparing to the length of the array).

    0 讨论(0)
  • 2020-11-30 02:06
        String[] nameArray= {"John", "Paul", "Ringo", "George"};
        int numberOfItems = nameArray.length;
        for (int i=0; i<numberOfItems; i++)
        {
            String name = nameArray[i];
            System.out.println("Hello " + name);
        }
    
    0 讨论(0)
  • 2020-11-30 02:13

    I would argue instead of testing i less than elements.length - 1 testing i + 1 less than elements.length. You aren't changing the domain of the array that you are looking at (i.e. ignoring the last element), but rather changing the greatest element you are looking at in each iteration.

    String[] elements = { "a", "a","a","a" };
    
    for(int i = 0; i + 1 < elements.length; i++) {
        String first = elements[i];
        String second = elements[i+1];
        //do something with the two strings
    }
    
    0 讨论(0)
  • 2020-11-30 02:15

    You have to maintain the serial how many times you are accessing the array.Use like this

    int lookUpTime=0;
    
        for(int i=lookUpTime;i<lookUpTime+2 && i<elements.length();i++)
         {
        // do something with elements[i]
        }
    
    lookUpTime++;
    
    0 讨论(0)
  • 2020-11-30 02:15

    As long as this question remains unsanswered the OP's problem and Java has evolved over the years, I have decided to put my own one.

    Let's change for sake of clarity the input String array to have 5 unique items.

    String[] elements = {"a", "b", "c", "d", "e"};
    

    You want to access two siblings in the list with each iteration incremented by one index.

    for (int i=0; i<elements.length-1; i++) {        // note the condition
        String left = elements[i];
        String right = elements[i+1];
    
        System.out.println(left + " " + right);      // prints 4 lines
    }
    

    Printing the pairs of left and right in four iterations result in the lines a b, b c, c d, d e in your console.

    What can happen if the input string array has less than 2 elements? Nothing prints our as long as this for-loop extracts always two sibling nodes. With less than 2 elements the program doesn't enter to the loop itself.

    As far as your snippet says you want to not discard the extracted values but add them an another variable, assuming outside the scope of the for-loop, you want to store them in either a list or an array. Let's say you want to concatenate the siblings with the + character.

    List<String> list = new ArrayList<>();
    String[] array = new String[elements.length-1];  // note the defined size
    
    for (int i=0; i<elements.length-1; i++) {
        String left = elements[i];
        String right = elements[i+1];
    
        list.add(left + "+" + right);            // adds to the list
        array[i] = left + "+" + right;           // adds to the array
    }
    

    Printing the contents both of the list and the array (Arrays.toString(array)) results in:

    [a+b, b+c, c+d, d+e]
    

    Java 8

    As of Java 8, you might be tempted to use the advantage of Stream API, however, it was made for procesing the individual elements from a source collection. There is no such method for processing 2 or more sibling nodes at once.

    The only way is to use Stream API to process the indices instead and map them to the real value. As long as you start with a primitive Stream called IntStream you need to use IntStream::mapToObj method to get boxed Stream<T>:

    String[] array = IntStream.range(0, elements.length-1)
        .mapToObj(i -> elements[i] + "+" + elements[i + 1])
        .toArray(String[]::new);                              // [a+b, b+c, c+d, d+e]
    
    List<String> list = IntStream.range(0, elements.length-1)
        .mapToObj(i -> elements[i] + "+" + elements[i + 1])
        .collect(Collectors.toList());                        // [a+b, b+c, c+d, d+e]
    
    0 讨论(0)
提交回复
热议问题