📜  foreach() 循环与流 foreach() 与并行流 foreach()

📅  最后修改于: 2021-09-12 10:51:36             🧑  作者: Mango

foreach() 循环

  • 不使用 Lambda运算符: Java中的 foreach 循环不使用任何 lambda 操作,因此操作可以应用于我们在 foreach 循环中用于迭代的列表之外的任何值。 foreach 循环关注通过将列表的每个元素存储在局部变量上并执行我们想要的任何功能来迭代集合或数组。
Java
public class GFG {
 
    public static void main(String[] args)
    {
        String[] arr = { "1", "2", "3" };
        int count = 0;
 
        String[] arr1 = { "Geeks", "For", "Geeks" };
 
        for (String str : arr) {
            System.out.print(arr1[count++]);
        }
    }
}


Java
public class GFG {
 
    public static void main(String[] args) throws Exception
    {
 
        String[] arr = { "1", "2", "3" };
        int count = 0;
 
        String[] arr1 = { "Geeks", "For", "Geeks" };
 
        for (String str : arr) {
            System.out.print(arr1[count++]);
        }
    }
}


Java
public class GFG {
 
    public static String frechlop(String[] geek)
    {
        int count = 0;
        for (String var : geek) {
            if (count == 1)
                return var;
            count++;
        }
        return "";
    }
 
    public static void main(String[] args)
        throws Exception
    {
 
        String[] arr1 = { "Geeks", "For", "Geeks" };
        String secelt = frechlop(arr1);
        System.out.println(secelt);
    }
}


Java
import Java.util.*;
public class GFG {
 
    public static void main(String[] args) throws Exception
    {
 
        List arr1 = new ArrayList();
        int count = 0;
        arr1.add("Geeks");
        arr1.add("For");
        arr1.add("Geeks");
        arr1.stream().forEach(s -> {
            // this will cause an error
            count++;
 
            // print all elements
            System.out.print(s);
        });
    }
}


Java
import java.util.*;
public class GFG {
 
    public static void main(String[] args) throws Exception
    {
 
        String[] arr1 = { "Geeks", "for", "Geeks" };
 
        // The next line will throw error
        // as there is no such method as stream()
        arr1.stream().forEach(
            s -> { System.out.print(s); });
    }
}


Java
import Java.util.*;
 
public class GFG {
 
    static String second(List list)
    {
        list.stream().forEach(
            s
            -> {
                // The next line will throw error
                // as no return allowed
 
                // if(s=="For")return s;
 
            });
        return "null";
    }
 
    public static void main(String[] args) throws Exception
    {
 
        List arr1 = new ArrayList();
        arr1.add("Geeks");
        arr1.add("For");
        arr1.add("Geeks");
        String f = second(arr1);
        System.out.println(f);
    }
}


输出:
GeeksForGeeks
  • 这里的 count 操作甚至可能是循环外的变量,因为它在 foreach 循环的范围内。
  • 它可用于所有集合和数组:它可用于迭代Java的所有集合和数组。

Java

public class GFG {
 
    public static void main(String[] args) throws Exception
    {
 
        String[] arr = { "1", "2", "3" };
        int count = 0;
 
        String[] arr1 = { "Geeks", "For", "Geeks" };
 
        for (String str : arr) {
            System.out.print(arr1[count++]);
        }
    }
}
输出:
GeeksForGeeks
  • return 语句在循环内工作:函数可以在循环内的任何时间点返回值。例如,如果我们只想打印任何集合或数组的前 2 个值,然后我们想返回任何值,则可以在Java 的foreach 循环中完成。下面的代码用于打印数组的第二个元素。

Java

public class GFG {
 
    public static String frechlop(String[] geek)
    {
        int count = 0;
        for (String var : geek) {
            if (count == 1)
                return var;
            count++;
        }
        return "";
    }
 
    public static void main(String[] args)
        throws Exception
    {
 
        String[] arr1 = { "Geeks", "For", "Geeks" };
        String secelt = frechlop(arr1);
        System.out.println(secelt);
    }
}
输出:
For

流().forEach()

  • 使用 Lambda运算符:在 stream().forEach() 中,使用了 lambda,因此不允许对循环外的变量进行操作。只能对相关集合进行操作。在这里,我们可以通过单行代码对集合执行操作,这使得编码变得容易和简单。

Java

import Java.util.*;
public class GFG {
 
    public static void main(String[] args) throws Exception
    {
 
        List arr1 = new ArrayList();
        int count = 0;
        arr1.add("Geeks");
        arr1.add("For");
        arr1.add("Geeks");
        arr1.stream().forEach(s -> {
            // this will cause an error
            count++;
 
            // print all elements
            System.out.print(s);
        });
    }
}
  • 注意:操作“count++”将导致错误,因为 lambda 操作不允许在其内部进行任何外部变量操作。
  • 仅用于迭代集合: stream().forEach() 仅用于访问集合,如 set 和 list。它还可以用于访问数组。

Java

import java.util.*;
public class GFG {
 
    public static void main(String[] args) throws Exception
    {
 
        String[] arr1 = { "Geeks", "for", "Geeks" };
 
        // The next line will throw error
        // as there is no such method as stream()
        arr1.stream().forEach(
            s -> { System.out.print(s); });
    }
}
  • Return 语句在这个循环中不起作用,但函数调用很容易调用:
    循环中的 return 语句不起作用。无法在相同的 forEach() 方法中完成获取第二个元素的相同功能。

Java

import Java.util.*;
 
public class GFG {
 
    static String second(List list)
    {
        list.stream().forEach(
            s
            -> {
                // The next line will throw error
                // as no return allowed
 
                // if(s=="For")return s;
 
            });
        return "null";
    }
 
    public static void main(String[] args) throws Exception
    {
 
        List arr1 = new ArrayList();
        arr1.add("Geeks");
        arr1.add("For");
        arr1.add("Geeks");
        String f = second(arr1);
        System.out.println(f);
    }
}
输出:
null

并行 foreach()

  • 适用于多线程概念: stream().forEach() 和并行 foreach() 之间的唯一区别是并行 forEach() 中给出的多线程功能。这比 foreach() 和 stream.forEach() 快得多。与 stream().forEach() 一样,它也使用 lambda 符号来执行功能。
    提供其多线程特性的示例如下。
    很明显,由于 parallelStream 的多线程性质,输出永远不会以相同的顺序打印字符串。

输出:
ForGeeksGeeks

表格差异

foreach() loop stream().foreach() loop parallelStream().foreach() loop
Lambda operators is not used Lambda operator is used Lambda operator is used
Can be used to access arrays and collections Can access collections only Can access collections only
The return or control statements work within the loop The return or control statements don’t work within the loop The return or control statements don’t work within the loop
No multithreading thus slow data is in sequence No multithreading thus slow data is in sequence It is multithreaded thus very fast and sequence is different