I have a list of int arrays. I want to group that by unique arrays.
int[] array1 = new int[]{1, 2, 3};
int[] array2 = new int[]{1, 2, 3}; //array1 = array2
int[] array3 = new int[]{0, 2, 3};
List<int[]> test = new ArrayList<>();
test.add(array1);
test.add(array2);
test.add(array3);
test.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Unfortunately, it doesn't work. It groups as if any array was unique:
{1, 2, 3} - 1
{1, 2, 3} - 1
{0, 2, 3} - 1
I expect:
{1, 2, 3} - 2
{0, 2, 3} - 1
What can I do?
It groups as if any array was unique:
And it is the case.
You would indeed have some difficulties to implement it whatever the way : built-in Collector
s such as groupingBy()
and toMap()
or loop as two arrays with the same content are not equals in terms of equals()
(and hashCode()
too).
You should consider to use List<Integer>
for this use case instead of int[]
.
For example :
public static void main(String[] args) {
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 1, 2, 3 }; // array1 = array2
int[] array3 = new int[] { 0, 2, 3 };
List<List<Integer>> test = new ArrayList<>();
test.add(Arrays.stream(array1)
.boxed()
.collect(Collectors.toList()));
test.add(Arrays.stream(array2)
.boxed()
.collect(Collectors.toList()));
test.add(Arrays.stream(array3)
.boxed()
.collect(Collectors.toList()));
Map<List<Integer>, Long> map = test.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map);
}
Output :
{[0, 2, 3]=1, [1, 2, 3]=2}
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