Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over static array in java without array variable

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?

like image 978
Xaq Avatar asked Jul 03 '13 16:07

Xaq


People also ask

How do you traverse an array of strings?

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

What are the different ways to iterate over an array in Java?

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.

What is the syntax to loop through array?

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.


2 Answers

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

like image 112
sanbhat Avatar answered Sep 30 '22 10:09

sanbhat


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.

like image 24
Jeffrey Avatar answered Sep 30 '22 09:09

Jeffrey