Count random single digits

The problem

Write a program that generates 100 random integers between 0 and 9 and displays the count for each number. (Hint: Use an array of ten integers, say counts, to store the counts for the number of 0s, 1s, . . . , 9s.)

Breaking it down

This example will use java 8 to generate random numbers within a range and then group each number using Collectors.groupingBy and Collectors.counting() to count the number of times a digits is chosen.

static final int SIZE = 100;
static final int RANGE = 10;

public static void main(String[] args) {

    Random random = new Random();
    Map<Object, Long> frequentNumbers = random.ints(0, RANGE).limit(SIZE)
            .boxed()
            .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

    frequentNumbers.forEach((k, v) -> System.out.println(k + ":" + v));
}

Output

0:11
1:9
2:16
3:11
4:14
5:5
6:6
7:12
8:10
9:6