Gandalf StormCrow
Gandalf StormCrow

Reputation: 26192

Maplike data structure

Is there a map like data structure with integer as key , string as value, which ends up to be sorted by key no matter on insertion order like when you insert first item {4, somevalue} that it will be on the fourth place when you use it in further application flow

Upvotes: 1

Views: 272

Answers (2)

polygenelubricants
polygenelubricants

Reputation: 383726

The interface SortedMap<K,V> defines a type that has the behavior you're looking for:

A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods).

A particular implementation of a SortedMap that may be of interest is a TreeMap:

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.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

Note that interface NavigableMap<K,V> extends SortedMap<K,V>. That is, a NavigableMap is a SortedMap, but it also specifies additional methods, e.g. all-inclusive bounds subMap. If you don't need these additional functionarlities, simply a SortedMap should work just fine.

See also


Example

This shows basic usage of NavigableSet<K,V>:

    NavigableMap<Integer,String> nmap =
        new TreeMap<Integer,String>();
    
    nmap.put(3, "Three");
    nmap.put(1, "One");
    nmap.put(4, "Four");
    nmap.put(5, "Five");
    nmap.put(7, "Seven");
    
    System.out.println(nmap);
    // {1=One, 3=Three, 4=Four, 5=Five, 7=Seven}

    System.out.println(nmap.firstKey()); // 1
    System.out.println(nmap.lastEntry().getValue()); // Seven
    System.out.println(nmap.higherKey(1)); // 3 
    System.out.println(nmap.lowerEntry(6).getValue()); // Five

    NavigableMap<Integer,String> sub = nmap.subMap(2, true, 5, true);
    for (Map.Entry<Integer,String> entry : sub.entrySet()) {
        System.out.printf("%s => %s%n",
            entry.getKey(),
            entry.getValue()
        );
    }
    // 3 => Three
    // 4 => Four
    // 5 => Five

Related questions

On basic Map manipulation:

Others of interest:

On SortedMap vs NavigableMap:

Upvotes: 2

andrewmu
andrewmu

Reputation: 14534

It sounds like you are looking for java.util.TreeMap<Integer, String>. It orders the entries based on the key.

Upvotes: 4

Related Questions