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 :
boîte le flux:
Arrays.stream(arr2).boxed();
@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
Vous pouvez utiliser ceci:
Integer[] arr = Arrays.stream(arr2).boxed().toArray(Integer[]::new);
Il n'y a pas de méthode encadrée
pour arr2
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)
Oh, j'ai utilisé la classe Stream de io.vavr
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>
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[]>
Double associé / possible de Comment puis-je convertir un Java 8 IntStream vers une liste? et / ou Comment faire convertir un tableau int en tableau entier en Java?