Programing

배열에서 스트림을 어떻게 만들 수 있습니까?

lottogame 2020. 7. 6. 07:50
반응형

배열에서 스트림을 어떻게 만들 수 있습니까?


현재 배열에서 스트림을 만들어야 할 때마다

String[] array = {"x1", "x2"};
Arrays.asList(array).stream();

배열에서 스트림을 생성하는 직접적인 방법이 있습니까?


Arrays.stream 예를 사용할 수 있습니다

Arrays.stream(array);

Stream.of@fge에서 언급 한 것처럼 사용할 수도 있습니다.

public static<T> Stream<T> of(T... values) {
    return Arrays.stream(values);
}

그러나 참고 Stream.of(intArray)는 반환 Stream<int[]>하는 반면 유형 배열을 전달 Arrays.stream(intArr)하면 반환됩니다 . 따라서 기본 유형의 요컨대 두 가지 방법의 차이점을 볼 수 있습니다.IntStreamint[]

int[] arr = {1, 2};
Stream<int[]> arr1 = Stream.of(arr);

IntStream stream2 = Arrays.stream(arr); 

프리미티브 배열을에 전달 Arrays.stream하면 다음 코드가 호출됩니다.

public static IntStream stream(int[] array) {
    return stream(array, 0, array.length);
}

기본 배열을 Stream.of다음 코드 로 전달하면 호출됩니다.

 public static<T> Stream<T> of(T t) {
     return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
 }

따라서 다른 결과를 얻습니다.

업데이트 : Stuart Marks 의견에서 언급했듯이 하위 범위 과부하는 Arrays.stream사용하는 것이 바람직 Stream.of(array).skip(n).limit(m)하지만 전자는 SIZED 스트림을 생성하지만 후자는 그렇지 않습니다. 그 이유는이 limit(m)반면, 크기가 m 이하 m 이상인지 여부를 모르는 Arrays.stream범위 검사를 수행하고 당신은에 의해 반환 스트림 구현을위한 소스 코드를 읽을 수있는 스트림의 정확한 크기를 알고 Arrays.stream(array,start,end) 여기를 스트림 구현에 의해 반환 된 반면, Stream.of(array).skip().limit()IS 이 방법 내에서 .


@ sol4me 솔루션의 대안 :

Stream.of(theArray)

이과의 차이 Arrays.stream(): 그것은 않습니다 배열은 원시적 형태의 경우 차이를 확인하십시오. 예를 들어, 다음과 같은 경우 :

Arrays.stream(someArray)

어디 someArray입니다 long[], 그것은을 반환합니다 LongStream. Stream.of()반면에, Stream<long[]>단일 요소와 함께 를 반환합니다 .


Stream.of("foo", "bar", "baz")

또는 이미 배열을 가지고 있다면 할 수도 있습니다

Stream.of(array) 

기본 유형 사용을 위해 IntStream.of또는 LongStream.of


병렬 옵션이있는 저수준 방법으로도 만들 수 있습니다.

업데이트 : 전체 array.length를 사용하십시오 (길이-1 아님).

/** 
 * Creates a new sequential or parallel {@code Stream} from a
 * {@code Spliterator}.
 *
 * <p>The spliterator is only traversed, split, or queried for estimated
 * size after the terminal operation of the stream pipeline commences.
 *
 * @param <T> the type of stream elements
 * @param spliterator a {@code Spliterator} describing the stream elements
 * @param parallel if {@code true} then the returned stream is a parallel
 *        stream; if {@code false} the returned stream is a sequential
 *        stream.
 * @return a new sequential or parallel {@code Stream}
 *
 * <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel)
 */

StreamSupport.stream(Arrays.spliterator(array, 0, array.length), true)

Arrays.stream을 사용할 수 있습니다.

Arrays.stream (배열); 

배열 입력 유형에 따라 증기의 반환 형식은이 경우 보장하지만 String []다음 반환 Stream<String>, 경우 int []다음 반환IntStream

입력 유형 배열을 이미 알고 있다면 입력 유형과 같은 특정 배열을 사용하는 것이 좋습니다 int[]

 IntStream.of (배열); 

Intstream을 반환합니다.

In first example, Java uses method overloading to find specific method based on input types while as in second you already know the input type and calling specific method.

참고URL : https://stackoverflow.com/questions/27888429/how-can-i-create-a-stream-from-an-array

반응형