To get a random element from a list is quite easy......you just have to get the element t the nth position where n is a random number. But A Set is an unordered collection so there is no question of any definite element at definite position.
In this situation the way to get a random element from a Set might not have a straightforward way.......But the thing that can be done is iterate through the set and get the nth element where n is a random number. Conceptually it's the same as getting a random element from a List or array.
Now suppose there is a Map with a String type as key and anything else say an Object as value...for example
where User is a Class and userMap holds the map between String id as key and user object as value.......to get a random user from this map we will use the above method in the example
Hence we can get a random elements through this method. we just got a set of String of keys of the map and then used the previous
Hope it helps.....
In this situation the way to get a random element from a Set might not have a straightforward way.......But the thing that can be done is iterate through the set and get the nth element where n is a random number. Conceptually it's the same as getting a random element from a List or array.
public String getRandomId(Set<String> idSet){
int Size = idSet.size();
int item = new Random().nextInt(Size);
return (String) idSet.toArray()[item];
}
Above method will return a random String from a Set of String........Now suppose there is a Map with a String type as key and anything else say an Object as value...for example
Map<String,User> userMap = new HashMap<String,User>();
where User is a Class and userMap holds the map between String id as key and user object as value.......to get a random user from this map we will use the above method in the example
String randomId = this.getRandomId(userMap.keySet());
User randomUser = userMap.get(randomId);
Hence we can get a random elements through this method. we just got a set of String of keys of the map and then used the previous
getRandomId
method to get a random key and got the corresponding value from the map.Hope it helps.....
No comments:
Post a Comment