從list中隨機選出幾個數,並按照原來的順序排列


需求:

從list中隨機選出幾個數,並按照原來的順序排列(比如從list中隨機選出6個數)

方案一:

//若對象size大於6,則隨機去除6個對象,並按照原來的順序排列
while(list.size() > 6) {
                //隨機取一個對象
             Long target = list.get(randomId.nextInt(list.size()));
             for(ListObject object : list) {
                     if(object.getId() == target) {
                                //將取出的那個對象刪除
                         list.remove(object);
                         break;
                     }
                 }        
}

方案二:

        //若list.size()大於6套,隨機產生6個對象,並按照原來的順序排列
        //若list的對象為ListObject
        if(list.size() > 6) {
            Random randomId = new Random();
            //對隨機的6個對象排成原來的默認順序
            List<Integer> indexes = new ArrayList<Integer>();
            while(indexes.size() < 6) {
                //對象在list里的位置
                int index = randomId.nextInt(list.size());
                if(!indexes.contains(index)) {
                    indexes.add(index);
                }
            }
            //對indexes排序
            Collections.sort(indexes);
            //取出indexes對應的list放到newList
            List<ListObject> newList = new ArrayList<ListObject>();
            for(int index : indexes) {
                newList.add(list.get(index));
            }
            list.clear();
            list.addAll(newList);
        }

分析:

考慮到性能問題,會考慮方案二,復雜度低,而且容易看懂。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM