Java对大量无序数据获取前N个的源码
工作闲暇时间,将做工程过程中重要的代码片段珍藏起来,下边代码段是关于Java对大量无序数据获取前N个的的代码,希望对大家有帮助。
public class LimitStorageList
{
    public LimitStorageList()
    { }
    public LimitStorageList(long maxTopN, List<KeyCountPair> list)
    {
        this.maxTopN = maxTopN;
        this.topNList = list;
    }
    void put(KeyCountPair keyCountPair)
    {
        {
            int index = isExist(keyCountPair);
            {
                topNList.add(keyCountPair);
                insertSort(topNList);
            }
            else
            {
                topNList.remove(keyCountPair);
                topNList.add(keyCountPair);
                insertSort(topNList);
            }
        }
        else
        {
            {
                int index = isExist(keyCountPair);
                {
                    topNList.set(topNList.size() - 1, keyCountPair);
                    insertSort(topNList);
                }
                else
                {
                    topNList.remove(keyCountPair);
                    topNList.add(keyCountPair);
                    insertSort(topNList);
                }
            }
        }
}
    private static void insertSort(List<KeyCountPair> topNList)
    {
        int i = topNList.size() - 1;
        KeyCountPair temp = topNList.get(i);
        int j = i - 1;
        for (; j >= 0 && (temp.compareTo(topNList.get(j)) == -1); j--)
        {
            topNList.set(j + 1, topNList.get(j));
        }
        topNList.set(j + 1, temp);
    }
    int isExist(KeyCountPair keyCountPair)
    {
        KeyCountPair keyCountPairTemp;
        for (int i = 0, length = topNList.size(); i < length; i++)
        {
            keyCountPairTemp = topNList.get(i);
            if (keyCountPairTemp.getKey().equals(keyCountPair.getKey()))
            {
                return i;
            }
        }
        return -1;
    }
...set,get...
}
                                
                        
                
                
            
            
                
posted on 2019-06-18 16:25 cottonwood 阅读(253) 评论(0) 收藏 举报
 
                    
                 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号