Keep a pair of primitives in Java HashMap
•
Java
I have a list of documents I want to scan and keep the number of files of the same size The problem is that the file size is very long. As we know, HashMap accepts only one object rather than one primitive So using the new long (file size), I put it into HashMap Since each long obj is unique, I get a (filesize, 1) list instead of a pair (filesize, count)
How do I build this accumulator?
1.4. 2 any solution?
Solution
You just do this:
Map<Long,Integer> count = new HashMap<Long,Integer>(); for (File file : files) { long size = file.getTotalSpace(); Integer n = count.get(size); if (n == null) { count.put(size,1); } else { count.put(size,n + 1); } }
Here are some auto boxing and unpacking
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码