Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Comparator for byte array (lexicographic)

I have a hashmap with byte[] keys. I'd like to sort it through a TreeMap.

What is the most effective way to implement the comparator for lexicographic order?

like image 400
marcorossi Avatar asked Feb 24 '11 17:02

marcorossi


1 Answers

Using Guava, you can use either of:

  • UnsignedBytes.lexicographicalComparator()
  • SignedBytes.lexicographicalComparator()

The UnsignedBytes comparator appears to have an optimized form using Unsafe that it uses if it can. Comments in the code indicate that it may be at least twice as fast as a normal Java implementation.

like image 182
ColinD Avatar answered Sep 28 '22 03:09

ColinD