In Ruby, I can do something like:
["FOO", "BAR"].each do { |str| puts str }
Iterating over an array defined in the statement in which I'm using it. Since I can define an array in Java like:
String[] array = { "FOO", "BAR" };
I know I can avoid defining the variable by setting up a loop like:
for (String str : new String[] { "FOO", "BAR" }) { ... }
But, I was hoping java might have something more terse, WITHOUT defining a variable containing the array first, and also allow me to avoid the dynamic allocation, is there a syntax like:
for (String str : { "FOO", "BAR" }) { ... }
That is more terse that will work with Java that I'm missing, or is the solution I've got above my only option?
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. }
Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.
The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.
The best you can do is
for(String s : Arrays.asList("a", "b")) {
System.out.println(s);
}
java.util.Arrays
gives a method asList(...)
which is a var-arg method, and it can be used to create List
(which is dynamic array) on fly.
In this way you can declare and iterate over an array in same statement
In Java 8, you will be able to do the following:
Stream.of("FOO", "BAR").forEach(s -> System.out.println(s));
This uses the new java.util.stream
package and lambda expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With