3
votes

Comment convertir Stream en Stream

Existe-t-il un moyen de convertir Stream> en Stream

int[] arr2 = new int[] { 54, 432, 53, 21, 43 };
// Below gives me Stream<int[]> 

Stream.of(arr2);  // I want to convert it to Stream<Integer>


5 Réponses :


4
votes

boîte le flux:

Arrays.stream(arr2).boxed();


3 commentaires

@AshishkumarSingh Si vous vraiment insisté pour commencer par Stream.of (arr2) , vous pouvez faire Stream.of (arr2) .flatMap (arr -> Arrays. stream (arr) .boxed ()) . Mais je ne sais pas pourquoi vous voudriez.


@Michael ou Stream.of (arr2) .flatMapToInt (Arrays :: stream) .boxed ()


@Holger Je cherchais ce que vous avez commenté. Je sais que cela n'a pas beaucoup de sens à utiliser lorsque nous avons Arrays.stream (arr2) .boxed () , mais je voulais juste savoir comment y parvenir si nous avons Stream



3
votes

Vous pouvez utiliser ceci:

Integer[] arr = Arrays.stream(arr2).boxed().toArray(Integer[]::new);


1 commentaires

Il n'y a pas de méthode encadrée pour arr2



1
votes

Vous pouvez créer un flux à partir de io.vavr avec

Arrays.stream(arr2)

mais vous souhaitez utiliser un flux d'entiers, vous devez utiliser IntStream. Vous pouvez créer IntStream à partir d'un tableau comme celui-ci:

Stream.ofAll(arr2)


1 commentaires

Oh, j'ai utilisé la classe Stream de io.vavr



4
votes

Vous pouvez utiliser soit Arrays.stream()

IntStream.of(arr2).boxed();   // will return Stream<Integer>

Ou IntStream.of

Arrays.stream(arr2).boxed();  // will return Stream<Integer>


0 commentaires

0
votes

Il y a un problème dans ce cas.

Prenons un exemple. Si vous avez un tableau de primitives et que vous essayez de créer un flux directement, vous aurez un flux d'un objet tableau comme celui-ci:

Arrays.stream(nums).count();  // Five Elements 
IntStream.of(nums).count(); // Five Elements

Pour résoudre ce problème, vous pouvez utiliser: p>

// Arrays of primitives 
int[] nums = {1, 2, 3, 4, 5}; 
Stream.of(nums); // One element int[] | Stream<int[]> 


0 commentaires