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
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.
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.
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With