Miguel
Miguel

Reputation: 11

Multi key, linked hash

I have a set of elements with two properties, a name (string, not unique) and id (integer, unique). All elements with the same name are stored together, sorted according to some criteria.

Insertion is done just once as all elements are known beforehand, so it can be done easily. Deletion is done according to either the order (the first one) or eventually the id. Reading the values will be the most common (and relevant) operation.

Performance is the top requirement for the data-structure. I thought a multikey, linked data structure or a mixed hashmap/stack would be ideal, but I know non. Some options I considered are: - Guava tables (multiple keys), but they don't have push/pop behaviors. - LinkedHashMaps, but they just have one key.

Of course I can use LinkedHasMaps and iterate for deletion for those cases in which I have to delete an element based on the id. I just want to know if there is something out there already implemented with high performance.

Any suggestions?

Thanks to everyone

Upvotes: 1

Views: 960

Answers (1)

therealrootuser
therealrootuser

Reputation: 10914

Use a Map<String, TreeSet<Integer>>. This will allow you to store several items under the same key, and keep the integer values sorted.


The idea is that you have a single key map to a data structure that can hold multiple values. To insert a name, value pair, you could do something like:

private Map<String, TreeSet<Integer>> map = new HashMap<>();

public void insert(String name, int value)
{
    if (! map.containsKey(name))
    {
        map.put(name, new TreeSet<Integer>());
    }
    map.get(name).add(value);
}

A LinkedHashMap just keeps track of insertion order of the keys, and iterates in that order--it wouldn't improve performance over using a HashMap.

Upvotes: 1

Related Questions