Java 陣列轉stream

  • Array
  • stream

前言

陣列轉stream可以透過Arrays.stream()或是Stream.of()來達成,但在面對物件陣列、基本型別陣列的返回略有不同

物件陣列轉stream

Arrays.stream(T[] array)Returns a sequential Stream with the specified array as its source.

 

Stream.of(T t)Returns a sequential Stream containing a single element.

public static void main(String[] args) {
	//Object array convert to stream
	String [] strs = {"Hello","Duke","Java"};
	Arrays.stream(strs).map(s->s.toUpperCase()).forEach(System.out::println);//HELLO DUKE JAVA
	Stream.of(strs).map(s->s.toLowerCase()).forEach(System.out::println);//hello duke java
}

基本型別陣列轉stream

stream(int[] array) Returns a sequential IntStream with the specified array as its source.

Stream.of(T t)Returns a sequential Stream containing a single element.

public static void main(String[] args) {	
	//primitive array convert to stream
	int [] nums = {1,2,3,4,5};
	Arrays.stream(nums).forEach(System.out::println);//此處返回的是IntStream,可以直接列印
	Stream.of(nums).forEach(System.out::println); //此處返回的是Stream<int[]>,無法直接列印數字
	Stream.of(nums).flatMapToInt(s->Arrays.stream(s)).forEach(System.out::println);//必須進行加工後才能直接列印
}

Stream.of其他用法

public static void main(String[] args) {
	Stream<String> stream1 = Stream.of("Hello","Duke","Java");
	Stream<Integer> stream2 =Stream.of(1,2,3,4);
}

Reference