I've seen many posts about how to randomly select an object from a set. In Java there are only two ways to do this that make sense.
Option 1: Select from a set by picking a random number ranging from 0 to the set's size and cycle through the set until you get to that position and return that object.
public Object randomlySelectObjectFromSetByPositionNumber(final Set<?> objects) {
if (objects != null && !objects.isEmpty()) {
final Random random = new Random();
final int position = random.nextInt(objects.size());
int pos = 0;
for (Object tmpString : objects) {
if (pos == position) {
return tmpString;
} else {
pos++;
}
}
LOGGER.warn("unable to select randomly from set - set exhausted");
return null;
} else {
return null;
}
}
Options 2: Convert the set to a list first, then pick a random number ranging from 0 to the list's size and get the object at the position.
public Object randomlySelectObjectFromList(final Set<?> objects) {
if (objects != null && !objects.isEmpty()) {
final List<Object> listCopy = new ArrayList<>();
listCopy.addAll(objects);
final Random random = new Random();
final int position = random.nextInt(listCopy.size());
return listCopy.get(position);
} else {
return null;
}
}
The question that should really be asked is, "Which of these is faster?" I will investigate and explain soon...
Option 1: Select from a set by picking a random number ranging from 0 to the set's size and cycle through the set until you get to that position and return that object.
public Object randomlySelectObjectFromSetByPositionNumber(final Set<?> objects) {
if (objects != null && !objects.isEmpty()) {
final Random random = new Random();
final int position = random.nextInt(objects.size());
int pos = 0;
for (Object tmpString : objects) {
if (pos == position) {
return tmpString;
} else {
pos++;
}
}
LOGGER.warn("unable to select randomly from set - set exhausted");
return null;
} else {
return null;
}
}
Options 2: Convert the set to a list first, then pick a random number ranging from 0 to the list's size and get the object at the position.
public Object randomlySelectObjectFromList(final Set<?> objects) {
if (objects != null && !objects.isEmpty()) {
final List<Object> listCopy = new ArrayList<>();
listCopy.addAll(objects);
final Random random = new Random();
final int position = random.nextInt(listCopy.size());
return listCopy.get(position);
} else {
return null;
}
}
The question that should really be asked is, "Which of these is faster?" I will investigate and explain soon...
No comments:
Post a Comment