Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream of integers

Tags:

java-8

I have the code:

int[] values = { 1, 4, 9, 16 };
Stream<Integer> ints = Stream.of(values);

which gives me compilation error. But:

int[] values = { 1, 4, 9, 16 };
Stream<Integer> ints = Stream.of(new Integer[] {1, 4, 9, 16});

doesn't give so. Why?

like image 687
user1539343 Avatar asked Jan 28 '17 21:01

user1539343


People also ask

What is integer stream?

An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.

What is the difference between stream and IntStream?

Stream<Integer> operates on boxed values ( Integer instead of primitive int) which takes significantly more memory and usually a lot of boxing/unboxing operations (depending on your code), whereas IntStream works with primitives.

How do you find the median of a stream of integers?

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. For example, for arr = [2,3,4] , the median is 3 . For example, for arr = [2,3] , the median is (2 + 3) / 2 = 2.5 .


2 Answers

In the first example, you are passing an array of primitives ints to Stream#of which can take either an object, or an array of object. Primitives are not objects.

In the second example, it compiles becauses you pass in an array of Integer.

You can use IntStream#of which accept int arrays.

like image 139
Jean-François Savard Avatar answered Nov 12 '22 00:11

Jean-François Savard


Because int[] and Integer[] is different types. First one is array of primitives, second one is array of objects with type Integer.

You can use IntStream.of(int[]) or Stream.of(Integer[])

like image 28
Vlad Bochenin Avatar answered Nov 11 '22 22:11

Vlad Bochenin