我有一组100个对象。 如何从这个集合中获取5个对象的子集?
我现在正在这样做,但它只返回一个对象
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;
}
答案 0 :(得分:16)
List<Member> list = new LinkedList<Member>(memberSet);
Collections.shuffle(list);
Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5));
完整示例:
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;
}
}
答案 1 :(得分:-1)
虽然@dacwe解决方案要好得多,但我无法帮助自己,在笑话上,只是说为所有内容添加for(int i = 0; i&lt; 5; i ++)并移出设置randomSet = new HashSet(); 在for循环之外: