1

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".

1
  • It is worth following up answers which are not acceptable because it may be that the question is unclear, could not have been reasonably answered or missing important details. Sometimes answers are not accepted because the questioner didn't like the answers given, e.g. "you can't do that" type answers. Commented Nov 8, 2012 at 13:32

2 Answers 2

5

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]
Sign up to request clarification or add additional context in comments.

2 Comments

An important detail to include. ;) In that case you need a custom Comparator. I assume you want "2AB" < "10A" ??
@mudit See above for an example
2

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.