Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach keyword in java?

I know the meaning of foreach in programming and when to use it. Is there a foreach keyword in Java? I tried to find a list of keywords but there is only for and not foreach.

like image 251
Shubhra Avatar asked Feb 28 '12 07:02

Shubhra


People also ask

What means forEach?

Foreach is a loop statement in the Perl programming language that executes once for each value of a data object. It takes the general form: foreach thing (in object) { do something; do something else; }

How do you use the forEach method?

JavaScript Array forEach() The forEach() method calls a function for each element in an array. The forEach() method is not executed for empty elements.

What is the advantage of forEach?

It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse the array or collection elements. The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

What does the forEach statement do?

The foreach statement: enumerates the elements of a collection and executes its body for each element of the collection. The do statement: conditionally executes its body one or more times.


1 Answers

As of Java 1.8, Java now has a foreach loop ...

package org.galarik.arick;

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

public class ExampleForEach {

    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        strings.add("Mom");
        strings.add("Dad");
        strings.add("Dad's Java");
        strings.add("Mom's Java");

        // Original for loop
        int stringsSize = strings.size();
        Object[] oldStrings = strings.toArray();
        for(int stringIndex = 0; stringIndex < stringsSize; ++stringIndex ) {
            System.out.println("Original Content: " + oldStrings[stringIndex]);
        }

        // For loop, as of Jova 1.5
        for (String string : strings) {
            System.out.println("All Content: " + string);
        }

        // forEach loop as of Java 1.8
        strings.stream().forEach((string) -> {
            System.out.println("For Content: " + string);
        });

        // Using forEach loop to do a filter
        strings.parallelStream().filter(someString -> someString.contains("Java"))
                .forEach((someOtherString) -> {
                    System.out.println("Content With Java: " + someOtherString);
                });
    }
}
like image 58
A. Rick Avatar answered Sep 29 '22 12:09

A. Rick