Listing random integers in Java (Scala style)

Is there an equivalent in Java 8 or later in Scala?

Seq.fill(n)(Random.nextInt)
+4
source share
2 answers

Perhaps a slightly closer approximation than Random.ints()would be something like this:

Stream
  .generate(rnd::nextInt)
  .limit(n)
  .collect(toList());

It is “closer” in the sense that if you ignore the minor syntactic differences and the difference Seqvs. List, both versions of Scala and this version are combined with a signature function

(Int, Unit => T) => Seq[T]

for any T:

(n, f) => Stream.generate(f).limit(n).collect(toList())
(n, f) => Seq.fill(n)(f)

Random.ints(), n, Scala. , , collect - Stream.


:

import java.util.stream.*;
import java.util.Random;
import java.util.List;
import static java.util.stream.Collectors.toList;

public class RandomListGeneration {
    public static void main(String args[]) {
        Random rnd = new Random();
        int n = 42;
        List<Integer> result = Stream
            .generate(rnd::nextInt)
            .limit(n)
            .collect(toList());
        System.out.println(result);
    }
}
+3

Random.ints(n) n. , , , :

int[] seq = rnd.ints(n).toArray();

, , :

List<Integer> list = rnd.ints(n).boxed().collect(toList());

, java.util.Random, , rnd . . , Random.next(bits) , . , :

: . . .

class MyRandom extends Random {
    int state = 0;
    protected int next(int bits) {
        return state ^= 1;
    }
}

Random rnd = new MyRandom();
int[] seq = rnd.ints(n).toArray();

API java.util.Random, , , , .

+6

Source: https://habr.com/ru/post/1695674/


All Articles