forEach in Java - ProgrammerTech
Language:

Search

forEach in Java

  • Share this:
forEach in Java

forEach concept in Java

The forEach() function, in this lesson we will talk about forEach() as it is in C# and PHP, you find it comes in abundance in C#. It is characterized by high efficiency, speed and short code more than the regular for, but the way to write it in Java is different from C# and PHP. The forEach() function is a function in the Interface Collection, which means that all classes derived from it, such as ArrayList, LinkedList, etc., are owned by it.

The forEach() function is a function that allows the user to access the elements of an object derived from the Interface Collection one by one.

Example

package foreach;
public class Foreach {
    public static void main(String[] args) {
        int []a={1,100,200,13};
        for(int i=0;i<a.length;i++)
            System.out.println(a[i]);
    }
}

This example was for a regular for, and the output will be printed as a loop for every number on a line.

 

Examples of using forEach

Example 1

Use numeric values ​​of type int.

package foreach;
public class Foreach {
    public static void main(String[] args) {
        int []a={1,100,200,13};
        for(int i:a)
            System.out.println(i);
    }
}

We used the forEach, first we created an integer array of type int and gave it four elements and then entered into a lobe loop. And we wrote int i:a, which means, store the elements of the array a inside i and then print it. And here we shortened a lot from the previous example, and this is the quality and technique of forEach, and the result will be the same.

Example 2

Use text values ​​of type String.

package foreach;
public class Foreach {
    public static void main(String[] args) {
        String []a={"data","kaissar","parrot","s49"};
        for(String i:a)
            System.out.println(i);
    }
}

In the beginning we created a text array of type String and gave it four text elements, then we entered a Loop loop and wrote int i:a that means store the elements of the array a inside i and then print it.


Tags:
Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com