Java streams: count distinct values in array of primitives

Arthur Borsboom :

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
Andronicus :

Because in the first one Stream.of method treats the whole array as one element - it creates a stream with an element of array. To work with array of primitives, you would have to use Arrays.stream instead.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=138944&siteId=1
Recommended