streams - Terminal Operations

本文深入探讨Java Stream API的使用,包括toArray方法的功能和用法,parallel操作如何将流转换为并行流,以及forEach和forEachOrdered方法的区别。通过具体代码示例,展示了如何利用这些方法进行高效的数据处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Convert to an Array

Object[] toArray()

Returns an array containing the elements of this stream.

This is a terminal operation.

Returns:

an array containing the elements of this stream

<A> A[] toArray(IntFunction<A[]> generator)

Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing.

This is a terminal operation.

API Note:

The generator function takes an integer, which is the size of the desired array, and produces an array of the desired size. This can be concisely expressed with an array constructor reference:


     Person[] men = people.stream()
                          .filter(p -> p.getGender() == MALE)
                          .toArray(Person[]::new);
 

Type Parameters:

A - the element type of the resulting array

Parameters:

generator - a function which produces a new array of the desired type and the provided length

Returns:

an array containing the elements in this stream

Throws:

ArrayStoreException - if the runtime type of the array returned from the array generator is not a supertype of the runtime type of every element in this stream

 

case 1:

// streams/RandInts.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package streams;

import java.util.*;
import java.util.stream.*;

public class RandInts {
  private static int[] rints = new Random(47).ints(0, 1000).limit(100).toArray();

  public static IntStream rands() {
    return Arrays.stream(rints);
  }
}

 

Apply a Final Operation to Every Element

S parallel()

Returns an equivalent stream that is parallel. May return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel.

This is an intermediate operation.

Returns:

a parallel stream

IntStream parallel()

Description copied from interface: BaseStream

Returns an equivalent stream that is parallel. May return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel.

This is an intermediate operation.

Specified by:

parallel in interface BaseStream<Integer,IntStream>

Returns:

a parallel stream

void forEach(Consumer<? super T> action)

Performs an action for each element of this stream.

This is a terminal operation.

The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism. For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.

Parameters:

action - a non-interfering action to perform on the elements

void forEachOrdered(Consumer<? super T> action)

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

This is a terminal operation.

This operation processes the elements one at a time, in encounter order if one exists. Performing the action for one element happens-before performing the action for subsequent elements, but for any given element, the action may be performed in whatever thread the library chooses.

Parameters:

action - a non-interfering action to perform on the elements

See Also:

forEach(Consumer)

// streams/ForEach.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import static streams.RandInts.*; // note this use

import java.util.*;
import java.util.stream.*;

public class ForEach {
  static final int SZ = 14;

  public static void main(String[] args) {
    rands().limit(SZ).forEach(n -> System.out.format("%d ", n));
    System.out.println();
    rands().limit(SZ).parallel().forEach(n -> System.out.format("%d ", n));
    System.out.println();
    rands().limit(SZ).parallel().forEachOrdered(n -> System.out.format("%d ", n));
  }
}
/* My Output:
258 555 693 861 961 429 868 200 522 207 288 128 551 589
551 589 258 207 555 693 128 861 288 200 961 429 522 868
258 555 693 861 961 429 868 200 522 207 288 128 551 589
*/

references:

1. On Java 8 - Bruce Eckel

2. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray--

3. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray-java.util.function.IntFunction-

4. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/RandInts.java

5. https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#ints-int-int-

6. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer-

7. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEachOrdered-java.util.function.Consumer-

8. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/ForEach.java

9. https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html#parallel--

10. https://docs.oracle.com/javase/8/docs/api/java/util/stream/BaseStream.html#parallel--

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值