简体   繁体   English

如何按前3名对ArrayList中的邮政编码列表进行排序?

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

Currently, I've got an ArrayList of zip codes which represent car accidents. 目前,我有一个表示交通事故的邮政编码ArrayList

Ex: 例如:

10005
10002
10003
10005
10004

In this case, I would like to count the highest occurrence of each of these zip codes and sort from highest to lowest. 在这种情况下,我想计算每个邮政编码的最高发生率,并从最高到最低排序。 I looked around and many people talked about using a HashMap to do this. 我环顾四周,许多人谈论使用HashMap来做到这一点。 Unfortunately, I cannot use a HashMap as per the directions on the homework. 不幸的是,我不能按照作业指导使用HashMap

What is the best way to count the frequency of each zip occurring, thus effectively counting the number of accidents per zip code without using a HashMap / Hashtable ? 什么是计算每个邮政编码发生频率,从而有效地计算每个邮政编码意外次数而不使用HashMap / Hashtable

I've thought about doing arrayOfZip[zipCode] = frequency and then sorting by there, but the problem with that is that the array declared will be unnecessarily huge in memory. 我考虑过要进行arrayOfZip[zipCode] = frequency ,然后在那里进行排序,但是这样做的问题是,声明的数组在内存中会不必要地庞大。

You can sort the list, and then iterate through counting how long the run of each zip code is; 您可以对列表进行排序,然后通过计算每个邮政编码的运行时间进行迭代。 then just keep track of the length of the 3 longest runs and their corresponding zip code. 然后只需跟踪3个最长行程的长度及其相应的邮政编码即可。

I think Colection Frequency based methods woulb be usuful: 我认为基于选择频率的方法会很有用:

int occurrences = Collections.frequency(zip, "xxxxxx"); int出现次数= Collections.frequency(zip,“ xxxxxx”);

Sort the list and then: 对列表进行排序,然后:

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
    }

This will essentially print the frequency of all unique zipcodes. 这实际上将打印所有唯一邮政编码的频率。 You can also always compare the counter and store the highest three frequency zipcodes. 您还可以始终比较计数器并存储最高频率的三个邮政编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM