There is a need to create a HashSet collection with 20 numbers from 0 to 20. When you create using the code written below, each time a collection is created with a random number of elements from random numbers. Tell me, please, why so? Indeed, in the cycle indicated the creation of 20 elements.

package level8; import java.util.*; public class task182_lev8_lec08 { public static HashSet<Integer> createSet() { int a = 20; HashSet<Integer> integerHashSet = new HashSet<>(); for (int i = 0; i < 20; i++){ double random = Math.random() * a; integerHashSet.add((int) random); } return integerHashSet; } public static void main(String[] args) { System.out.println(createSet()); } } 
  • one
    Set can contain only unique elements. If several identical numbers are created in the loop, only one will be saved. - Sergey Gornostaev
  • create a HashSet collection with 20 numbers from 0 to 20 Ie 20 out of 21 possible? Isn't it easier to unconditionally create 21, from 0 to 20, and then delete one random? - Akina

2 answers 2

It's HashSet. If identical elements come across, he does not add it. Simply replace it with a List, or add say, say print somewhere, you will see it.

In order for it to work you need to do this:

 int counter = 0; while (counter < 20) { double random = Math.random() * a; if (integerHashSet.add((int) random)) { counter++; }; } 

    I can offer this solution:

     private static Set<Integer> getRandomSet(int count) { return new Random() .ints(0, 20) .distinct() .limit(count) .boxed() .collect(Collectors.toSet()); } 
    • Frankly speaking, nothing is clear, I just started learning and did not even get to that) - Stanley Kubrik
    • This is stream api. Nothing complicated - ints returns a stream of random int from a range from 0 to 20, distinct removes duplicates, limit limits the number of elements, boxed converts an int to Integer, collect collects what happened in the Set - Artem Konovalov collection