DerBenniAusA
DerBenniAusA

Reputation: 807

Simplify unique String check in a Set

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

Answers (1)

f1sh
f1sh

Reputation: 11944

The main purpose of Set is to guarantee that there are no duplicate elements. adding 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

Related Questions