I have an arraylist that contains some arrays, I want to print out the arraylist, if an array in the arraylist is repeated then print it only one time with a number of occurences next to it. (Assumes all arrays are sorted from smallest to biggest)
Here is my current code:
public static void main(String[] args) {
int[] a1 = {1,2,3,4,5};
int[] a2 = {1,2,3,4,5};
int[] a3 = {1,2,3,4,5};
int[] a4 = {2,5,7,8,9};
int[] a5 = {2,5,7,8,9};
int[] a6 = {3,4,6,8,9};
ArrayList<int[]> list = new ArrayList<>();
list.add(a1);
list.add(a2);
list.add(a3);
list.add(a4);
list.add(a5);
list.add(a6);
for (int i = 0; i < list.size(); i ) {
System.out.println(Arrays.toString(list.get(i)));
}
}
Here is the output that I want:
1,2,3,4,5 (3)
2,5,7,8,9 (2)
3,4,6,8,9
(If it unique then don't need occurences number)
Thank you very much for your help!
CodePudding user response:
Use List<Integer>
instead of int[]
, because List’s equals()
(and hashCode()
) method can be used to good effect.
Assuming:
List<List<Integer>> list = new ArrayList<>();
list.add(List.of(1,2,3,4,5));
// etc
Then it’s a one-liner:
list.stream().distinct().forEach(System.out::println);