簡體   English   中英

如何按前3名對ArrayList中的郵政編碼列表進行排序?

[英]How do I sort a list of zip codes in an ArrayList by the top 3?

目前,我有一個表示交通事故的郵政編碼ArrayList

例如:

10005
10002
10003
10005
10004

在這種情況下,我想計算每個郵政編碼的最高發生率,並從最高到最低排序。 我環顧四周,許多人談論使用HashMap來做到這一點。 不幸的是,我不能按照作業指導使用HashMap

什么是計算每個郵政編碼發生頻率,從而有效地計算每個郵政編碼意外次數而不使用HashMap / Hashtable

我考慮過要進行arrayOfZip[zipCode] = frequency ,然后在那里進行排序,但是這樣做的問題是,聲明的數組在內存中會不必要地龐大。

您可以對列表進行排序,然后通過計算每個郵政編碼的運行時間進行迭代。 然后只需跟蹤3個最長行程的長度及其相應的郵政編碼即可。

我認為基於選擇頻率的方法會很有用:

int出現次數= Collections.frequency(zip,“ xxxxxx”);

對列表進行排序,然后:

int counter;
for(int i=0;i<SizeOfList;i+=counter)
//increment counter by no. of times a zipcode occurred to avoid repetation
    {
        counter=1;
        for(j=i+1;j<SizeOfList;++j)
            { 
                if(zipcode[i]==zipcode[j])//checking one zipcode with all next values in list
                    counter++;
            }
        System.out.print("\nFrequency of " + zipcode[i] + " is " + counter);
//getting the frequency of that zipcode and printing it(can store it if you want) 
//Next it will jump the loop by value of counter and hence
//the next zipcode inline will come into loop and it will continue till end
    }

這實際上將打印所有唯一郵政編碼的頻率。 您還可以始終比較計數器並存儲最高頻率的三個郵政編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM