当前位置:网站首页>Randomly fetch data from the list

Randomly fetch data from the list

2022-06-13 05:33:00 zrllllll

Because I encountered this problem when writing the project , You need to implement this method , I searched the Internet , Found out Collections.shuffle() This method .shuffle Shuffle the cards 、 hold ··· Change position 、 transfer .

// Sort the set randomly 
Collections.shuffle(list);
int randomSeriesLength = 5;
// Take out the first five 
List<HotUser> randomSeries = list.subList(0, randomSeriesLength);

This is the code example I used , When the last one is returned, you can find list Five pieces of random data in the set .
Next, let's look at the source code .
stay Collections There are two static methods in the class shuffle.

public static void shuffle(List<?> list) {
    
        Random rnd = r;
        if (rnd == null)
            r = rnd = new Random(); // harmless race.
        shuffle(list, rnd);
    }

private static Random r;
public static void shuffle(List<?> list, Random rnd) {
    
		//list length 
        int size = list.size();
        // Less than adjustment threshold (SHUFFLE_THRESHOLD = 5) Or support fast random access 
        //RandomAccess when List Implementations use markup interfaces to indicate that they support fast ( It's usually a constant time ) Random access .  The main purpose of this interface is to allow common algorithms to change their behavior , To provide good performance when applied to random or sequential access lists .
        if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
    
            for (int i=size; i>1; i--)
            // Swap two elements at a specified location 
                swap(list, i-1, rnd.nextInt(i));
        } else {
    
        // If it is greater than the threshold or does not support fast random access, it will be converted to an array for processing 
            Object arr[] = list.toArray();

            // Shuffle array
            for (int i=size; i>1; i--)
                swap(arr, i-1, rnd.nextInt(i));

            // Dump array back into list
            // instead of using a raw type here, it's possible to capture
            // the wildcard but it will require a call to a supplementary
            // private method
            // Put the array back into the collection again 
            ListIterator it = list.listIterator();
            for (int i=0; i<arr.length; i++) {
    
                it.next();
                it.set(arr[i]);
            }
        }
    }
原网站

版权声明
本文为[zrllllll]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280510456288.html