This is just a map/reduce problem. Use Hadoop. It's Java, isn't it?
Note that you can easily reach 1TB of RAM on (enterprise) commodity hardware now, and SSDs are pretty fast too.
Old but gold post from 2014: https://adamdrake.com/command-line-tools-can-be-235x-faster-...