Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java streams: count distinct values in array of primitives

Why does a distinct count of an int array return a different result than a count of an Integer array? I would expect a result of 3 in both cases.

int[] numbers1 = { 1, 2, 3 };
System.out.println("numbers1: " + Arrays.toString(numbers1));
System.out.println("distinct numbers1 count: " + Stream.of(numbers1).distinct().count());

Integer[] numbers2 = { 1, 2, 3 };
System.out.println("numbers2: " + Arrays.toString(numbers2));
System.out.println("distinct numbers2 count: " + Stream.of(numbers2).distinct().count());

Results

numbers1: [1, 2, 3]
distinct numbers1 count: 1

numbers2: [1, 2, 3]
distinct numbers2 count: 3
like image 859
Arthur Borsboom Avatar asked Aug 30 '19 14:08

Arthur Borsboom


People also ask

How do I get unique values from a collection stream?

Processing only Unique Elements using Stream distinct() and forEach() Since distinct() is a intermediate operation, we can use forEach() method with it to process only the unique elements.

How do I use distinct in stream?

distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not necessarily stable and can change.

How do you count streams in Java?

Stream count() method in Java with exampleslong count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation).


1 Answers

In your first case, the type of Stream.of(numbers1) is Stream<int[]> and it only has one value in it.

In your second case, the type of Stream.of(numbers2) is Stream<Integer> and it has 3 distinct values in it.

You an use IntStream.of(1, 2, 3) to get a stream of primitive int.

like image 96
Erwin Bolwidt Avatar answered Oct 11 '22 15:10

Erwin Bolwidt