Reputation: 25534
I have a hashmap, I wish to get an array of the keys in this hashmap, but I wish for the array to be sorted.
For instance if the map looks like this:
<"2",obj1>
<"4",obj2>
<"6",obj3>
<"10",obj4>
<"5",obj5>
<"1",obj6>
<"15",obj7>
<"3",obj8>
I want the array to be: ["1", "2", "3", "4", "5", "6", "10", "15"]
The faster the better. Is there a built in way to do this?
Update 1
When i am using TreeMap, keys are sorted in following order:
"1", "10", "2" and so on.
but i want them to be like: "1","2","3".. "10","15".
Upvotes: 1
Views: 2512
Reputation: 533620
I have some keys like "10A", "2AB"
In that case you need a custom comparator like
public static void main(String... args) {
NavigableMap<String, Object> map = new TreeMap<String, Object>(new Comparator<String>() {
final Pattern pattern = Pattern.compile("(\\d+)(.*)");
@Override
public int compare(String o1, String o2) {
Matcher matcher1 = pattern.matcher(o1);
Matcher matcher2 = pattern.matcher(o2);
matcher1.find();
matcher2.find();
int cmp = Long.compare(Long.parseLong(matcher1.group(1)), Long.parseLong(matcher2.group(1)));
if (cmp != 0)
return cmp;
return matcher1.group(2).compareTo(matcher2.group(2));
}
});
map.put("1", "one");
map.put("1A", "oneA");
map.put("10", "ten");
map.put("10AB", "tenAB");
map.put("15", "fifteen");
map.put("2", "two");
map.put("2AB", "twoAB");
map.put("2", "three");
System.out.println(map.keySet());
}
prints
[1, 1A, 2, 2AB, 10, 10AB, 15]
Upvotes: 5
Reputation: 951
if converting your code to a naturally sorted Map is not an option for some reason, there are built in tools to return the key set and sort it manually -
Object[] keys = yourMap.keySet().toArray();
Arrays.sort(keys);
System.out.println(Arrays.toString(keys));
Upvotes: 2