Reputation: 807
I wanna generate unique String Ids until it is unique.
My approach is:
private Set<String> uniqueIdSet = new HashSet<>();
...
boolean contains = uniqueIdSet.contains(getRandomId());
while (contains){
var randomId = getRandomId();
contains = uniqueIdSet.contains(randomId);
if (!contains){
uniqueIdSet.add(randomId);
}
}
My question: is there a better way to implement this?
Upvotes: 0
Views: 64
Reputation: 11944
The main purpose of Set is to guarantee that there are no duplicate elements. add
ing an element already checks for that.
Use the return value of add
to see if the id was already in the Set
:
String randomId = getRandomId();
while (!uniqueIdSet.add(randomId)) {
randomId = getRandomId();
}
EDIT: Take a look at Andreas's comment above, which is even better.
Upvotes: 4