Java List Random Item pickRandom(LinkedList list, int n)

Here you can find the source of pickRandom(LinkedList list, int n)

Description

pick Random

License

Mozilla Public License

Declaration

public static <T> LinkedList<T> pickRandom(LinkedList<T> list, int n) 

Method Source Code

//package com.java2s;
//License from project: Mozilla Public License 

import java.util.LinkedList;
import java.util.Random;

public class Main {
    public static <T> LinkedList<T> pickRandom(LinkedList<T> list, int n) {
        if (n <= 0)
            throw new IllegalArgumentException("Parameter n must be > 0");
        if (n > list.size())
            return list;
        int l = list.size();
        LinkedList<T> temp = list;
        LinkedList<T> res = new LinkedList<T>();
        Random r = new Random();
        int index;
        int remaining = l;
        for (int i = 0; i < n; i++) {
            index = r.nextInt(remaining);
            remaining--;//  w  ww .j av a2 s .  c  o  m
            res.add(temp.get(index));
            temp.remove(index);
        }
        return res;
    }
}

Related

  1. nextElement(List list)
  2. nextRandomElement(final List list)
  3. pickNAtRandom(List vals, int n, long seed)
  4. pickOneAtRandom(List list)
  5. PickRandom(final Collection list)
  6. pickRandom(List collection)
  7. pickupFromList(String[] list)
  8. resampleWithReplacement(final List l, final int n)
  9. sample(List l, Random r)