- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieving Elements from Collection in Java- For-each loop
The ‘for-each’ loop is used to iterate over a set of elements that is stored in a data structure.
Syntax
for (element e: collection) { System.out.println(e); }
Example
Following is an example −
public class Demo { public static void main(String[] args) { int[] my_vals = {5, 67, 89, 31, -1, 2, 0}; int sum = 0; for (int number: my_vals) { sum += number; } System.out.println("The sum is " + sum); } }
Output
The sum is 193
A class named Demo contains the main function that defines an integer array with certain values. A sum is initially defined as 0, and the array is iterated over, and every element in the array is added to the sum. This final result is displayed on the screen.
- Related Articles
- Retrieving Elements from Collection in Java- Iterator
- Retrieving Elements from Collection in Java- ListIterator
- Retrieving Elements from Collection in Java- EnumerationIterator
- Retrieving Elements from Collection in C#
- Retrieving specific documents from collection by _id in MongoDB
- How does the java "for each" loop works
- How to limit the number of records, while retrieving data from a MongoDB collection using Java?
- Retrieving the first document in a MongoDB collection?
- How to use for each loop through an array in Java?
- How to iterate a List using for-Each Loop in Java?
- Retrieving MySQL Database structure information from Java?
- How to iterate a Java List using For-Each Loop?
- Java for loop
- How to retain elements from a Collection in another Collection
- Add all the elements from a collection to the HashSet in Java

Advertisements