We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,571 Members — Technology Publication meets Social Media

# Count the amount of a value in array/arraylist

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?

4
Contributors
3
Replies
1 Day
Discussion Span
7 Months Ago
Last Updated
4
Views
efth
Newbie Poster
21 posts since May 2012
Reputation Points: 0
Skill Endorsements: 0

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

zeroliken
Nearly a Posting Virtuoso
1,346 posts since Nov 2011
Reputation Points: 214
Skill Endorsements: 15

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

jalpesh_007
Posting Whiz
350 posts since Sep 2010
Reputation Points: 4
Skill Endorsements: 5

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.

piyush09
Newbie Poster
8 posts since Apr 2008
Reputation Points: 10