Reputation: 695
I have written a piece of logic, where, my goal is to select random keys from the map. The map has been assigned as a ConcurrentSkipListMap<Text,IntWritable> tuples
. Also, I don't have any industrial level experience with Java, so struggling to get over this.
The piece of code is
Set<Text> keys = tuples.keySet();
String randomKeys = keys.get(random.netInt(keys.size()))
I am not able to figure out the error statement: method get(int) is undefined for the type Set<Text>
Also, I have searched for the similar problem, and a solution do exist using List
, but my key/value pairs are stored as ConcurrentSkipListMap
, so not able to figure out this.
Thanks.
Upvotes: 1
Views: 14437
Reputation: 830
A Set does not have an get() method, because its not array like.
you normaly can iterate through an Set with its iterator: set.iteraor().next()
The iterator interface implements the folowing methods:
public boolean hasNext()
public E next()
public void remove()
you can use it like here (in this case is an Set):
Iterator it = set.iterator();
while (it.hasNext())
{
String setText = (String) it.next();
System.out.println(setText);
}
Upvotes: 0
Reputation: 201497
First, Set
doesn't have a get()
method. You could use a List
. Also, it's Random.nextInt()
List<Text> keys = new ArrayList<>(tuples.keySet());
Text randomKeys = keys.get(random.nextInt(keys.size()));
Also, depending on your use-case I believe it would likely be better to Collections.shuffle(List)
once and then iterate it (perhaps with a for-each
loop) like
List<Text> keys = new ArrayList<>(tuples.keySet());
Collections.shuffle(keys);
for (String randomKey : keys) {
// ...
}
Upvotes: 4