Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a random subset from a result set in java

Tags:

java

random

set

I have a set of 100 object. How can i get a subset of 5 objects from this set ?

I'm doing this for now but it only returns me one object

          int size = memberSet.size();
      Set<Member> randomSet = new HashSet<Member>();
            int item = new Random().nextInt(size);
            int i = 0;
            for(Member mbr : memberSet)
            {
                if (i == item){
                    randomSet.add(mbr);
            }
                i = i + 1;
            }
like image 468
Kévin_Bransard Avatar asked Aug 25 '11 13:08

Kévin_Bransard


People also ask

How do you return a random element from a set?

In order to get random elements from the HashSet object, we need to generate a random number between 0 (inclusive) and the size of the HashSet (exclusive). And then iterate through the set till we reach the element located at the random number position as given below.

How do you randomly select from a list in Java?

Picking a Random Item/Items In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method. The key point here is to remember that you mustn't use an index that exceeds your List's size.

How to generate a random index in Java?

Math. random() generates a random number between 0 and 1. If you multiply that number by the length of your array, you will get an random index for the array.


1 Answers

List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));

Full example:

public static void main(String... args) {

    Set<Member> memberSet = new HashSet<Member>();
    for (int i = 0; i < 100; i++)
        memberSet.add(new Member(i));

    List<Member> list = new LinkedList<Member>(memberSet);
    Collections.shuffle(list);
    Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));

    System.out.println(randomSet);
}

static class Member {
    final int value;
    public Member(int value) {
        this.value = value; 
    }
    @Override
    public String toString() {
        return "" + value;
    }
}
like image 129
dacwe Avatar answered Sep 18 '22 09:09

dacwe