متد sortAndCount در ورودی آرایه نامرتب ids رو میگیره و در خروجی یک آرایه دو بعدی که دو سطر داره (سطر اول برای آی دی ها و سطر دوم برای تعداد دفعات تکرارشون).
با مثالی که وجود داره، فکر میکنم عملکردش واضح باشه.
import java.util.Arrays;import java.util.LinkedList;
import java.util.Queue;
public class Test {
/**
* @param ids
* @return sorted 2D array - first row for ids and second row for counts
*/
public static int[][] sortAndCount(int[] ids) {
int lastElement, count;
Queue<Integer> sortedIds = new LinkedList<>();
Queue<Integer> sortedCounts = new LinkedList<>();
Arrays.parallelSort(ids);
lastElement = ids[0];
count = 1;
for (int i = 1; i < ids.length; i++) {
if (lastElement == ids[i]) {
count++;
} else {
sortedIds.add(lastElement);
sortedCounts.add(count);
lastElement = ids[i];
count = 1;
}
}
sortedIds.add(lastElement);
sortedCounts.add(count);
// Convert to 2D array & invert
int[][] outputArray=new int[2][sortedIds.size()];
for(int i=outputArray[0].length-1;i>=0;i--){
outputArray[0][i]=sortedIds.poll();
outputArray[1][i]=sortedCounts.poll();
}
return outputArray;
}
public static void main(String[] args) {
int[] ids=new int[]{4858,4020,4858,4858,1020,4020,1020};
int[][] sortedList = Test.sortAndCount(ids);
for(int i=0;i<sortedList[0].length;i++){
System.out.println(sortedList[0][i]+"--"+sortedList[1][i]);
}
}
}
خروجی:
4858--3
4020--2
1020--2