Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a pair of primitives in a Java HashMap

I have a list of files. I would like to scan through and keep a count of the number of files with the same size. the issue is with filesize which is a long, as we know, hashmap will take in only an object and not a primitive. So using new Long(filesize), I put it into the hashmap. instead of getting a pair of (filesize, count), I got a list of (filesize, 1) due to the fact that each Long obj is unique.

How do I go about building this accumulator?

Any solution for 1.4.2?

like image 349
zeroin23 Avatar asked May 24 '09 04:05

zeroin23


1 Answers

You simply do it this way:

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);
  }
}

There is some auto-boxing and unboxing going on here.

like image 181
cletus Avatar answered Nov 10 '22 16:11

cletus