Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by for a list of int arrays [duplicate]

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?

like image 480
Aleksandr Avatar asked Mar 12 '18 11:03

Aleksandr


1 Answers

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 Collectors 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}

like image 182
davidxxx Avatar answered Nov 14 '22 20:11

davidxxx