Re: [Vala] sorted keys from a hash



On Sat, Feb 13, 2010 at 21:59:20 +0530, Martin DeMello wrote:
On Sat, Feb 13, 2010 at 3:39 AM, Jan Hudec <bulb ucw cz> wrote:
On Sat, Feb 13, 2010 at 02:54:21 +0530, Martin DeMello wrote:
What's the most efficient (in terms of speed) way to iterate over a
hash in sorted order of the keys? The keys are strings.

To use a balanced tree.

Hash can only ever be iterated in the hash order, which is fixed but
pseudo-random.

Well, here's my exact problem: I have a TreeMap that I add (string,
string) pairs to. The desired output is a sorted list of these pairs.
Now I'm wondering if it'd be more efficient to use a HashMap instead,
since I don't really need to maintain the sorted property as the list
is built up, just have it sorted when I return it. Roughly, I want

It most probably would not.

What should be actually more efficient is to collect the pairs into an
ArrayList, sort it and copy out the values.

for i in map.keys.sort() {
  retval.append (i, map[i])
}

return retval

except I've been through the API and I can't find a good way to sort
the keys, or to push the pairs into a list and sort the list.

There is Gee.AbstractList.sort(CompareFunc?). Collect the pairs into
Gee.ArrayList and use .sort on it.

On a side note, Vala currently does not share strings, but you can move them
with (owned) "cast" to avoid some copying ((owned) transfers ownership and
nulls it's operand).

-- 
                                                 Jan 'Bulb' Hudec <bulb ucw cz>



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]