Get a random subset from the result set in Java
•
Java
I have a set of 100 objects
I'm doing this now, but it only returns 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; }
Solution
List<Member> list = new LinkedList<Member>(memberSet);
List<Member> list = new LinkedList<Member>(memberSet); Collections.shuffle(list); Set<Member> randomSet = new HashSet<Member>(list.subList(0,5));
Complete 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; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码