EN
Java - get random element from HashSet
0
points
In this article, we would like to show you how to get a random element from HashSet in Java.
1. Using for loop
In this example, we generate a random number between 0
and HashSet size
. Then we iterate through the HashSet till we reach the element located at the randomNumber
position.
import java.util.*;
public class Example {
public static void main(String[] args) {
Set<String> letters = new HashSet<>();
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");
int size = letters.size();
int randomNumber = new Random().nextInt(size);
int i = 0;
for (String letter : letters) {
if (i == randomNumber)
System.out.println(letter);
i++;
}
}
}
Output:
B
2. Using iterator
In this example, we generate a random number between 0
and HashSet size
. Then using iterator we iterate through the HashSet till we reach the element located at the randomNumber
position.
import java.util.*;
public class Example {
public static void main(String[] args) {
Set<String> letters = new HashSet<>();
letters.add("A");
letters.add("B");
letters.add("C");
letters.add("D");
letters.add("E");
System.out.println(getRandomElement(letters));
}
private static <String> String getRandomElement(Set<String> hashset) {
int randomNumber = new Random().nextInt(hashset.size()); // generate random number
Iterator<String> iterator = hashset.iterator();
int index = 0; // current index
String randomElement = null; // random element to return
while (iterator.hasNext()) {
randomElement = iterator.next();
if (index == randomNumber) // if current index is equal to random number
return randomElement;
index++;
}
return randomElement;
}
}
Output:
E
3. By converting HashSet to Array
In this example, we convert numbers
HashSet into an array and then access the random element from it.
import java.util.*;
public class Example {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
Integer[] lettersArray = numbers.toArray(new Integer[numbers.size()]);
int randomNumber = new Random().nextInt(numbers.size());
System.out.println(lettersArray[randomNumber]);
}
}
Output:
2