Doubt with parameter in Java 8 to generate random numbers using Collectors.toList () [closed]

0

I have this method to generate random numbers in ArrayList ;

public static List<Integer> gerarAleatorio() {

        List<Integer> aleatorios = new ArrayList<>();

        while(aleatorios.size() < 6) {

            int num = (int) (1  + Math.random() * 60);

            if(!aleatorios.contains(num)) {
                aleatorios.add(num);
            }

        }
        return aleatorios;
    } 

My question is why I can not do this method like this:

public static void gerarAleatorio(List<Integer> lista) {
lista = aleatorios.stream().collect(Collectors.toList());

and receive the random list at the end, with Collectors .

    
asked by anonymous 22.12.2016 / 19:37

1 answer

3

Try to do this:

private static int gerarNumeroAleatorio() {
    return (int) (1 + Math.random() * 60);
}

public static List<Integer> gerarAleatorio() {
    return Stream.generate(EstaClasse::gerarNumeroAleatorio)
        .distinct()
        .limit(6)
        .collect(Collectors.toList());
}

Explanation:

The gerarNumeroAleatorio() method is self-explanatory.

The gerarAleatorio() method starts with ...

  • ... an infinite sequence of elements provided by the gerarNumeroAleatorio() method, ...

  • ... but without repeating elements, ...

  • ... limited to only 6 elements (and therefore ceasing to be infinite) and ...

  • ...

  • ...
22.12.2016 / 21:34