Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key/Value Collection that maintains order

I need a delphi key/value collection that will allow me to iterate over the collection in the same order the key/value pairs were inserted/added.

TList<T> guarantees order but TDictionary<T1, T2> does not.

I guess I could always define a TList<TPair<Key, Value>> but it would be more cumbersome to work with.

Is there a built-in collection type that would meet my requirements or would wrapping TList<TPair<Key, Value>> be my best option? Or perhaps it would be better to have a TList<Key> and a TDictionary<Key, Value> and iterate through the list.

like image 485
Kenneth Cochran Avatar asked Oct 31 '11 15:10

Kenneth Cochran


People also ask

Does ArrayDeque maintain insertion order?

ArrayDeque a deque can used for simple que and stack so you want to have ''first in first out'' or ''first in last out'' behaviour, both require that the ArrayDeque maintains insertion order. In this case the insertion order is maintained as a central part of the classes contract.

Which maintains key-value pair of data?

A key-value database stores data as a collection of key-value pairs in which a key serves as a unique identifier. Both keys and values can be anything, ranging from simple objects to complex compound objects.

Which type of collection contains key-value pairs *?

Every dictionary is an unordered collection of key-value pairs. You can iterate over a dictionary using a for - in loop, decomposing each key-value pair into the elements of a tuple.

Does Java map keep order?

It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is,when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted.


2 Answers

If your key type is string and your value type is some descendant of TObject, use a TStringList. Store your values in the Objects array property.

SL.AddObject('foo', obj1);

SL.Add('bar');
i := SL.IndexOf('bar');
SL.Objects[i] := obj2;

Set the OwnsObjects property if you need to.

like image 175
Rob Kennedy Avatar answered Oct 08 '22 14:10

Rob Kennedy


the DeHL collections library contains a lot of "Ordered Dictionary"-like classes. The ordered ones use trees (which have order) instead of hash maps which are unordered.

I believe the TSortedDistinctMultiMap might be what you need, if you want to enforce uniqueness, and if you don't want to enforce Key value uniqueness, then there are other choices (without Distinct in the class name) that will be close to what you need.

Update 2017: The DeHL library is no longer maintained.

like image 33
Warren P Avatar answered Oct 08 '22 15:10

Warren P