Query with Java 8 parameter to generate random numbers using Collectors.toList()

Asked

Viewed 76 times

0

I have this method to generate random numbers in a 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’t do this method:

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

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

  • 1

    The second code is incomplete. Try to complete it so the answer can be appropriate.

  • It gives some compilation error saying that aleatorios was not declared in its second method? Moreover, where does its second method call the Math.random()?

1 answer

3

Try to do so:

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 method gerarNumeroAleatorio() is self-explanatory.

Already the method gerarAleatorio(), begins with...

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

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

  • ... limited to only 6 elements (and therefore no longer infinite) and ...

  • ... collect the result of this turning it into a list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.