开发者

Get a random subset from a result set in java

开发者 https://www.devze.com 2023-03-30 22:30 出处:网络
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

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){
      开发者_如何学Go              randomSet.add(mbr);
            }
                i = i + 1;
            }


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;
    }
}


Although @dacwe solution is much better I can't help myself, on joke, to just say put a for(int i=0; i<5; i++) around everything and move out the Set randomSet = new HashSet(); Outside the for loop :

0

精彩评论

暂无评论...
验证码 换一张
取 消