Iterate over static array in java without array variable

array-initialization, arrays, foreach, iteration, java

Solution

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

Problem

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?

Original source

Related problems