17

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?

2
  • 1
    Good question. It would be interesting to see if there's any easier way to define literal data structures. Commented Jul 3, 2013 at 16:41
  • 1
    Just found this (nearly identical) question while surfing: stackoverflow.com/questions/2358866/… Commented Jul 3, 2013 at 17:07

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Since Java 11, you can replace Arrays.asList with List.of. And also String with var, because the type can be inferred from the types in the list.
6

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.

1 Comment

Thanks -- I thought Java8 might add something like that.
2

Languages like Java are incredibly verbose compared to terse languages like Ruby. It looks to me like what you already have is your best bet:

for (String str : new String[] { "FOO", "BAR" }) { ... }

Comments

1

I think your question is about syntactic sugar for collections as much as anything. However, in Java 8 you can say

Arrays.asList("a", "b").forEach(System.out::println);

where you can of course substitute your own method literal that's compatible with Consumer<T>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.