-3
Arraylist al = new ArrayList();

Random r = new Random();

int arr[] = new int[100];

for (int i = 0; i < arr.length; i++) { // assuming the array variable is named arr...
    arr[i] = r.nextInt(200);
    al.add(arr[i]);
}

Output should be like this

Duplicates:2

Values 2 : count=4

Values 99: count=96

Without using hash things Jdk 1.6_04

2 Answers2

2

A simpler solution would be:

al.stream().distinct()
                .forEach(v -> System.out.println("Values " + v + " : count=" + Collections.frequency(al, v)));

Get a stream consisting of the distinct elements then count the number of elements in the list with Collections.frequency()

Update: if you're not allowed to use features of java 8:

Set<Integer> distinctSet = new HashSet<>(al);
for(int i: distinctSet) {
    System.out.println("Valuess " + i + " : count=" + Collections.frequency(al, i));
}
Hülya
  • 3,353
  • 2
  • 12
  • 19
0

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126