Java Arrays stream(int[] a) 方法



描述

Java Arrays stream(int[] a) 方法返回一個包含指定陣列所有元素的 IntStream。

宣告

以下是 java.util.Arrays.stream(int[] a) 方法的宣告

public static IntStream stream​(int[] array)

引數

a − 這是一個數組,假設在使用期間不會被修改。

返回值

此方法返回一個包含陣列元素的流。

異常

Java Arrays stream​(int[] a, int fromIndex, int toIndex) 方法

描述

Java Arrays stream(int[] a, int fromIndex, int toIndex) 方法返回一個包含指定陣列指定範圍內的元素的 IntStream。

宣告

以下是 java.util.Arrays.stream(int[] a, int fromIndex, int toIndex) 方法的宣告

public static IntStream stream​(int[] array, int fromIndex, int toIndex)

引數

  • a − 這是一個數組,假設在使用期間不會被修改。

  • fromIndex − 這是要包含的第一個元素的索引(包含)。

  • toIndex − 這是要包含的最後一個元素的索引(不包含)。

返回值

此方法返回一個包含陣列元素的流。

異常

  • ArrayIndexOutOfBoundsException − 如果 fromIndex < 0 或 toIndex > array.length

整數陣列流示例

以下示例演示了 Java Arrays stream(int[]) 方法的用法。首先,我們建立了一個整數陣列。然後使用 stream() 方法列印陣列。

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {
      // initialize array
      int arr[] = { 11, 54, 23, 32, 15, 24, 31, 12 };

      System.out.print("Array: [ ");

      // use the stream to print each item
      Arrays.stream(arr).forEach(i -> System.out.print(i + " "));
      
      System.out.print("]");
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Array: [ 11 54 23 32 15 24 31 12 ]

使用範圍的整數陣列流示例

以下示例演示了 Java Arrays stream(int[], int, int) 方法的用法。首先,我們建立了一個整數陣列。然後使用 stream() 方法列印陣列。

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {
      // initialize array
      int arr[] = { 11, 54, 23, 32, 15, 24, 31, 12 };

      System.out.print("Array: [ ");

      // use the stream to print each item
      Arrays.stream(arr, 0, arr.length).forEach(i -> System.out.print(i + " "));
      
      System.out.print("]");
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Array: [ 11 54 23 32 15 24 31 12 ]

整數子陣列流示例

以下示例演示了 Java Arrays stream(int[], int, int) 方法的用法。首先,我們建立了一個整數陣列。然後使用 stream() 方法列印子陣列。

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {
   public static void main(String[] args) {
      // initialize array
      int arr[] = { 11, 54, 23, 32, 15, 24, 31, 12 };

      System.out.print("Array: [ ");

      // use the stream to print each item
      Arrays.stream(arr, 0, 5).forEach(i -> System.out.print(i + " "));
      
      System.out.print("]");
   }
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Array: [ 11 54 23 32 15 ]
java_util_arrays.htm
廣告