Home > Mobile >  Avoid inserting duplicate value to a list in Java
Avoid inserting duplicate value to a list in Java

Time:12-02

So I want to insert random integers to a list. However, I want to make sure that there are no duplicates on the list. Here is what I have done so far:

while (options.size() <=4) {
    int i = 0;
    int random = ThreadLocalRandom.current().nextInt(answer - 8 ,answer   8);
    if (random != answer && random != options.get(i-1)) {
        options.add(random);
        i  ;
    }
}

CodePudding user response:

The easiest way is with a distinct random stream:

ThreadLocalRandom.current()
        .ints(answer - 8, answer   8)
        .distinct()
        .limit(5)
        .forEach(options::add);

For better performance on bigger datasets, you can shuffle instead:

List<Integer> range = IntStream.range(answer - 8, answer   8)
        .boxed()
        .collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(range);
options.addAll(range.subList(0, 5));

CodePudding user response:

It turns out all I needed was the contain function

while (options.size() <=4){
        int i = 0;
        int random = ThreadLocalRandom.current().nextInt(answer -8 ,answer  8 );
        if (random != answer && !options.contains(random)){
            options.add(random);
            i  ;
        }

    }
  • Related