syntagma
syntagma

Reputation: 24344

Java Map data structure that recognizes order of Integers stored as Strings

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?

Upvotes: 1

Views: 126

Answers (2)

brb tea
brb tea

Reputation: 343

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.

Upvotes: 2

chiastic-security
chiastic-security

Reputation: 20520

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.

Upvotes: 1

Related Questions