Dave's Brain

Browse - Programming Tips - Hashes don't promise any order for keys. Is there a way to keep the keys sorted?

Date: 2015dec15
Language: Java
Keywords: HashMap, Hash

Q.  Hashes don't promise any order for keys.  Is there a way to keep the keys sorted?

A.  Use a TreeMap

It is sorted by the ascending order of the keys - ie alphabetical order.

The official documentation says:

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.