33

Given the following exists in a class, how do I write a for-each that prints each item in the list?

private ArrayList<String> list;
list = new ArrayList<String>();

I have:

for (String object: list) {
    System.out.println(object);
}
2
  • 15
    @Xaerxess it's faster that way Commented Mar 21, 2012 at 21:49
  • I was just wondering if that was right, but i guess it is. Commented Mar 21, 2012 at 21:57

2 Answers 2

93

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}
Sign up to request clarification or add additional context in comments.

Comments

36
import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

1 Comment

Welcome to StackOverflow! Code-only answers are often considered not so helpful. Please add some explanation about how this solves OP's question.

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.