This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Array List Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array List" Watch "Array List" New topic
Author

Array List

James Tok
Greenhorn

Joined: May 19, 2010
Posts: 4
Good day,
I have a list as below

----------
A
A
B
B
B
C
C
C
----------

how can i get something as below: which the number indicates the # repeated in the list?
----------
A,2
B,3
C,3
----------

i only know that i could use HashSet to eliminate the duplicates... but how to display the number?

Thank.

Carey Brown
Ranch Hand

Joined: Nov 19, 2001
Posts: 173

Instead of HashSet, use HashMap with a value of type Integer to keep the count in.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4523
    
    5

You need to use a java.util.Map


luck, db
There are no new questions, but there may be new answers.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11150
    
  16

You will need to build the data. What the above folks are suggesting is as follows...

define a map with a String as the key, and an Int as the value.

read through your array, one at a time.

For each element, check the map to see if the current element exists as a key

If not, add it in with '1' as the value

If so, increment the counter that currently exists.

When you have gone through the array list, you can get a list of all the keys, and then use that to get all the values.


OR...

If your input will definitely be nothing more than single characters, you can accomplish the same thing with a 26 element array of ints.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array List
 
Similar Threads
Reference to a LABEL
Q how does the above code give error and the code below doesn't???
Generics question List with super
casting int to Byte
Take the Dr. Phil Test