ArrayList in java, only doing an action once
For some reason, I'm drawing a blank on this one. I have an ArrayList that contains CDs (some of them identic开发者_C百科al in name) and I want to print a String that tells how many I have of each CD. For example, a string that says "You have: (1) AlbumOne, (2) AlbumTwo, (1) AlbumThree" etc. The CDs are not sorted. How can I do this?
One way to do it is to loop thru the array, and use a map that uses the objects as keys and the values as counts. So
Map<YourObject, Integer> counter ...
As you loop thru the array, do a get
on the counter for the current object in the array. If you get null, initialize the value at that bucket in the map to be 1. If you have a value, increment it. Then you can loop over the map to get your readout.
Note that if you use a Hashmap
, your objects have to implement the hashcode
and equals
method properly. You don't have to use your object, if it has keys or some other distinguishing field, the keys in your map can be that...
//aggregate details
Map<String, Integer> albumCounts = new HashMap<String, Integer>();
for (String album : albums) {
Integer count = albumCounts.get(album);
if (count == null) {
count = 0;
}
albumCounts.put(album, count + 1);
}
//print stats
System.out.println("You have:");
for (String album : albums) {
System.out.println("(" + albumCounts.get(album) + ") " + album);
}
Don't get confused about the Map
. Use of Map
is appropriate to solve such a problem (as you have posted) So please visit this link (tutorial) and read/learn about Map.
精彩评论