Vala Collections Examples

List Example

This sample uses the List class from GLib. There is also various container classes in libgee, which are often easier to use or more powerful. See ../GeeSamples

int main (string[] args) {
    var list = new List<string> ();
    list.append ("one");
    list.append ("two");
    list.append ("three");
    
    stdout.printf ("list.length () = %u\n", list.length ());

    // Traditional iteration
    for (int i = 0; i < list.length (); i++) {
        stdout.printf ("%s\n", list.nth_data (i));
    }

    // Comfortable iteration
    foreach (string element in list) {
        stdout.printf ("%s\n", element);
    }

    return 0;
}

Compile and Run

$ valac list.vala
$ ./list

HashTable Example

int main (string[] args){
    var hash = new HashTable<string,string>(str_hash, str_equal);
    hash.insert("1", "one");
    hash.insert("2", "two");

    foreach(string key in hash.get_keys()){
        stdout.printf ("%s => %s \n", key, hash.lookup(key));
    }

    return 0;
}

Compile and Run

$ valac hashmap.vala
$ ./hashmap


Vala/Examples

Projects/Vala/CollectionsSample (last edited 2020-07-28 22:00:10 by Gavr Maxutenko)