1

I have the following data:

"1" --> "Label 1"
"2" --> "Label 2"
"11" --> "Label 11"
"22" --> "Label 22"

which I would like to store in a map that would enforce order of integers, instead of lexicographic order. Is there any *Map that Java already has for this purpose?

1
  • 1
    Use a TreeMap and provide your own Comparator that orders by integer value. Commented Nov 13, 2014 at 17:05

2 Answers 2

2

Use TreeMap with custom Comparator.

Like:

    TreeMap<String, String> map = new TreeMap<>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2));
        }
    });

The keys will be ordered according to passed Comparator.

Above is just example, but based on your usecase you may change implementation of compare() to reflect your business need.

Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't work if the values get really big and can be negative, because the difference can overflow.
@chiastic-security if values too big, then it will not overflow, but will throw Exception. As OP has only informed about Integer type, and it is solution of that.
No, I don't mean too big to be parsed. I mean that each one is a valid Integer, but the difference is bigger than Integer.MAX_VALUE. That won't throw an exception, it'll just give wrong answers (which is worse).
@chiastic-security I updated my answer. And thanks for suggesting integer overflow.
1

Yes, you can use a TreeMap or a ConcurrentSkipListMap, each of which implements SortedMap, and allows you to provide a Comparator at map creation time.

Either implement it as going from Integer as the key, or leave it as a String but supply a comparator that works by converting to Integer and using that for comparison.

I'd have thought it would be cleaner to use Integer as the key, but it won't make much difference.

If you go down the String route, do it like this. It's the same as Huko's code, but doesn't go wrong with large negative values where the difference might cause an overflow.

TreeMap<String, String> map = new TreeMap<>(new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
        return Integer.parseInt(o1).compareTo(Integer.parseInt(o2));
    }
});

EDIT: Huko's code now takes this into account too.

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.