📜  Java中的 IntStream 并行()

📅  最后修改于: 2022-05-13 01:55:26.976000             🧑  作者: Mango

Java中的 IntStream 并行()

IntStream parallel()是Java.util.stream.IntStream 中的一个方法。此方法返回一个并行 IntStream,即它可能返回自身,因为流已经存在,或者因为底层流状态被修改为并行。

IntStream parallel() 是一个中间操作。这些操作总是懒惰的。在 Stream 实例上调用中间操作,在它们完成处理后,它们给出一个 Stream 实例作为输出。

句法 :

IntStream parallel()

Where, IntStream is a sequence of 
primitive int-valued elements and the function 
returns a parallel IntStream.

下面给出了一些示例,以更好地理解该函数。
示例 1:

// Java program to demonstrate working of
// IntStream parallel() on a given range
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a stream of integers
        IntStream stream = IntStream.range(5, 12);
  
        System.out.println("The corresponding " + 
                         "parallel IntStream is :");
        stream.parallel().forEach(System.out::println);
    }
}

输出 :

The corresponding parallel IntStream is :
9
8
11
10
6
5
7

示例 2:

// Printing sequential stream for the 
// same input as above example 1.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        IntStream stream = IntStream.range(5, 12);
  
        System.out.println("The corresponding " + 
                      "sequential IntStream is :");
        stream.sequential().forEach(System.out::println);
    }
}

输出 :

The corresponding sequential IntStream is :
5
6
7
8
9
10
11

示例 3:

// Java program to show sorted output
// of parallel stream.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a stream of integers
        IntStream stream = IntStream.of(3, 4, 1, 5, 2, 3, 9);
  
        System.out.println("The sorted parallel" + 
                              " IntStream is :");
        stream.parallel().sorted().forEach(System.out::println);
    }
}

输出 :

The sorted parallel IntStream is :
4
2
3
1
3
5
9

请注意,它仍然显示为未排序。那是因为正在使用 forEach()。要按排序顺序处理项目,请使用 forEachOrdered()。但请注意,这否定了使用并行的优势。