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]