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 :
精彩评论