Iterate through string array in Java

JavaArraysCollections

Java Problem Overview


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 component and the component next to that one. So the first time I would get the component number one and the component number 2, the second time would get the number 2 and 3, the third time number 3 and 4... And so on until you get to the last component.

This how far I have come:

String[] elements = { "a", "a","a","a" };
    
for( int i = 0; i <= elements.length - 1; i++)
{
    // get element number 0 and 1 and put it in a variable, 
    // and the next time get element      1 and 2 and put this in another variable. 
}

How can I accomplish this?

Java Solutions


Solution 1 - Java

You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:

String[] elements = {"a", "a", "a", "a"};   
for (String s: elements) {           
    //Do your stuff here
    System.out.println(s); 
}

Solution 2 - Java

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.

Solution 3 - Java

String current = elements[i];
if (i != elements.length - 1) {
   String next = elements[i+1];
}

This makes sure you don't get an ArrayIndexOutOfBoundsException for the last element (there is no 'next' there). The other option is to iterate to i < elements.length - 1. It depends on your requirements.

Solution 4 - Java

String[] elements = { "a", "a","a","a" };

for( int i=0; i<elements.length-1; i++)
{
    String s1 = elements[i];
    String s2 = elements[i+1];
}

Solution 5 - Java

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
}

Solution 6 - Java

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++;

Solution 7 - Java

    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);
    }

Solution 8 - Java

Those algorithms are both incorrect because of the comparison:

> for( int i = 0; i < elements.length - 1; i++)

or

> for(int i = 0; i + 1 < elements.length; i++) {

It's true that the array elements range from 0 to length - 1, but the comparison in that case should be less than or equal to. Those should be:

> for(int i = 0; i < elements.length; i++) {

or

> for(int i = 0; i <= elements.length - 1; i++) {

or

> for(int i = 0; i + 1 <= elements.length; i++) {

The array ["a", "b"] would iterate as:

> i = 0 is < 2: elements[0] yields "a" > > i = 1 is < 2: elements[1] yields "b"

then exit the loop because 2 is not < 2.

The incorrect examples both exit the loop prematurely and only execute with the first element in this simple case of two elements.

Solution 9 - Java

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

Solution 10 - Java

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]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionErikssonEView Question on Stackoverflow
Solution 1 - JavaMichalView Answer on Stackoverflow
Solution 2 - JavaStefan KendallView Answer on Stackoverflow
Solution 3 - JavaBozhoView Answer on Stackoverflow
Solution 4 - JavaascanioView Answer on Stackoverflow
Solution 5 - JavaILMTitanView Answer on Stackoverflow
Solution 6 - JavaRaselView Answer on Stackoverflow
Solution 7 - JavaRavichandra S VView Answer on Stackoverflow
Solution 8 - JavaTrustButVerifyView Answer on Stackoverflow
Solution 9 - JavaMarco Carlo MoriggiView Answer on Stackoverflow
Solution 10 - JavaNikolas CharalambidisView Answer on Stackoverflow