1

Stream.of(int[]) returns Stream<int[]>, whereas Stream.of(String[]) returns Stream<String>.

Why are the two methods are behaving differently? Both should have either returned Stream<int> and Stream<String> or Stream<int[]> and Stream<String[]>.

static int intArr[] = { 1, 2, 3, 4, 5 }; 
static String stringArr[] = { "3", "6", "8","14", "15" }; 

Stream<int[]> stream = Stream.of(intArr);
Stream<String> stream1 = Stream.of(stringArr);
khelwood
  • 55,782
  • 14
  • 81
  • 108
Vaibhav Mittal
  • 145
  • 2
  • 8
  • 1
    Because primitives don't work well with generics. The `int[]` is interpreted as one object, and is thus one element in the array passed to `Stream.of`. – Slaw May 26 '19 at 07:11
  • 1
    `Stream.of(int[])` cannot return a `Stream` because an `int` is not an `Object`. – khelwood May 26 '19 at 07:11
  • When you pass `String[]` array to `Stram::of` it will be interpreted as if you passed strings one by one because of `varargs` parameter of `Stram::of` method. – Michał Krzywański May 26 '19 at 07:13
  • ok , i understood the difference now , when I changed array from int to Integer then it is returning correctly Stream stream = Stream.of(intArr); Thanks all :) – Vaibhav Mittal May 26 '19 at 07:18
  • Related: https://stackoverflow.com/questions/31422025/arrays-aslistint-not-working – Slaw May 26 '19 at 07:19

1 Answers1

5

There's no such thing Stream<int>, just like there's no List<int>. Generic type parameters cannot be substituted with primitive types.

For a stream of (primitive) int elements there's IntStream. IntStream.of(int... values) and Arrays.stream(int[] array) will both give you an IntStream, whose elements are int, where you pass an int[] to them.

Eran
  • 387,369
  • 54
  • 702
  • 768