I'm storing tons of Java UUID
into a HashMap
as row using UUID.toString()
. Since the data is huge, soon it throws OutOfMemoryError
. Now I'm thinking about a compact way to represent the UUID
, preferably something like long
, and then later I can easily reconstruct the UUID
with that long
representation. Is this possible?

- 17,079
- 6
- 43
- 66

- 4,799
- 24
- 67
- 124
2 Answers
I'm storing tons of Java
UUID
into aHashMap
as row usingUUID.toString()
.
So by this you mean HashMap<String, MyObject>
?
Storing UUID itself via HashMap<UUID, MyObject>
will conserve space compared to HashMap<String, MyObject>
. A UUID
takes up less space than the String
does (two long
values become 16 bytes versus char[36]
for 72 bytes, that'll save you almost 80% space right there).
If changing that's not enough, then consider whether or not the UUID
values are important across JVM's. If the ID only needs to be unique for a single process (are you saving the HashMap
to disk or sharing it between Java processes?), then you can just use int
since a HashMap
can't be any bigger than Integer.MAX_VALUE
anyway. So instead of HashMap<UUID, MyObject>
, you'd have HashMap<Integer, MyObject>
. Even better, you can use Short
if you are going to have less than 216 objects, saving even more space. However, if you're getting an OutOfMemoryError
, I suspect you probably have more than 65536 objects.
Lastly, if all else fails, allocate more memory to your JVM as demonstrated in this question.
A UUID is fundamentally a number, but it's a 128-bit number, which is twice the size of a java long. You could use BigInteger (which is probably no more space-efficient than storing UUIDs as strings), or you could encapsulate the UUID in an object that contains two longs — one for the first 64 bits and one for the last 64 bits.
Given the UUID 550e8400-e29b-41d4-a716-446655440000
, you would want to create two longs, one containing the number 0x550e8400e29b41d4
, and one containing the number 0xa716446655440000
.

- 223,387
- 19
- 210
- 288