I think there is more to this and we will need more details from you. I assume that you know that there are definitely more than one file of a given size, otherwise I will first check that this happens. As far as you know, you just have a lot of files with unique file sizes.
You mentioned:
... because each Long obj is unique.
I do not think this is a problem. While this may be true depending on how you create Longs, this should not stop HashMaps from behaving the way you want. As long as the two key objects return the same hashCode () value and the equals () method says they are equal, your HashMap will not create another record for it. In fact, you will not be able to see the "list (filesize, 1)" with the same file size values ββ(unless you wrote your own Long and were unable to properly implement hashCode () / equals ()).
However, Cletus code should work if you use Java 5 or later, if you use Java 1.4 or lower, you need to either manually do your boxing / unboxing or look into the Apache Community Collections . Here's the pre-Java 5 version of the Cletus example:
Map count = new HashMap(); for (Iterator filesIter = files.iterator(); filesIter.hasNext();) { File file = (File)filesIter.next(); long size = file.getTotalSpace(); Integer n = count.get(size); if (n == null) { count.put(size, Integer.valueOf(1)); } else { count.put(size, Integer.valueOf(n.intValue() + 1)); } }
Jack leow
source share