Here's one way to go about it:
new Random().ints(100, 0, 200) // 100 is streamSize , 0 is randomNumberOrigin, 200 is randomNumberBound
.boxed()
.collect(groupingBy(Function.identity(), counting()))
.forEach((k, v) -> System.out.println("Values " + k + " count" + v));
or if you want the result in a list:
List<String> result = new Random().ints(100, 0, 200) // 100 is streamSize , 0 is randomNumberOrigin, 200 is randomNumberBound
.boxed()
.collect(groupingBy(Function.identity(), counting()))
.entrySet().stream()
.map(e -> "Values " + e.getKey() + " count" + e.getValue())
.collect(Collectors.toList());
Another approach would be with toMap
:
List<String> res = new Random().ints(100, 0, 200) // 100 is streamSize , 0 is randomNumberOrigin, 200 is randomNumberBound
.boxed()
.collect(toMap(Function.identity(), e -> 1, Math::addExact))
.entrySet().stream()
.map(e -> "Values " + e.getKey() + " count" + e.getValue())
.collect(Collectors.toList());
Edit:
given you've removed the Java 8 tag, here's a solution for completeness:
List<Integer> al = new ArrayList<>();
Set<Integer> accumulator = new HashSet<>();
Random r = new Random();
for (int i = 0; i < 100; i++) {
int result = r.nextInt(200);
al.add(result);
accumulator.add(result);
}
for (Integer i : accumulator) {
System.out.println("Values " + i + " : count=" + Collections.frequency(al, i));
}
+1 to @Hülya for suggesting Collections.frequency
first.