Let's say I have an array/arraylist(doesn't matter) with the following content: 2, 2, 2, 4, 5, 5, 8, 8, 8.
How wold I go about counting the different values, in other words; how would I find out that there are 3 twos, one 4, 2 fives and 3 eights.
How would like to get an attay(or arraylist for that matter) with the content: 3, 1, 2, 3.
How would I go about doing that?

Recommended Answers

All 3 Replies

use an array that increments its element depending on the value of the reference array/arraylist as you iterate over it
the index of the counting array would depend on which value the current reference array has

you can also use the map/Hashmap for that.take key as integer as input like 2,3,8 and add subsequent counter in value part of that particular key.

You can easily find how many times 2, 3 or occured in your array/arraylist.

Thank you

Using a Map is better approach, because if you use Array then you can not devide the size of array incase input have two digits two degits numbers even if input has single digits arrays should be of size 10, But Map will have the values and their count that are present in the input.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.