Skip to main content

6.5 Collections and Data Structures in Julia

Documentation

Arrays

Arrays are ordered collection of elements. In Julia they are automatically indexed (consecutively numbered) by an integer starting with 1.

Creating arrays

ActionSyntax
New array (empty)[]
Specify type (integer)Int64[]
Specify type (string)String[]
Array with values[1, 2, 3, 4, 5]
Array with values["a1", "b2", "c3"]
Array of numberscollect(1:10)

Creating array from string

ActionSyntax
Split string str by delimiter into words (e.g., space)split(str, " ")

Accessing elements

ActionSyntax
Get length of array my_arraylength(my_array)
Get first element of array my_arraymy_array[1]
Get last element of array my_arraymy_array[end]
Get n element of array my_array (e.g., 2)my_array[2]
Check if element is in arrayin(str, my_array)

Adding and removing elements

ActionSyntax
Add element to endpush!(my_array, str)
Remove element from endpop!(my_array)
Remove element from beginningpopfirst!(my_array)
Add element to beginningpushfirst!(my_array, str)

Sort and unique

ActionSyntax
Sort array (will not change array itself)sort(my_array)
Sort array in place (will change array)sort!(my_array)
Get unique elements in arrayunique(my_array)

Compare arrays

ActionSyntax
Intersectionintersect(my_array, your_array)
Unionunion(my_array, you_array)

Convert array to string

ActionSyntax
Convert array to stringjoin(collect(my_array), str)

Input:

# arrays.jl

day_array = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
day = "Thursday"

array_length = length(day_array)
array_first_day = day_array[1]
array_last_day = day_array[end]

println("Length of array: $array_length")
println("First day of week: $array_first_day")
println("Third day of week: $(day_array[3])")
println("Last day of week: $array_last_day")

println("$day is in $day_array: $(in(day, day_array))")

# add Sunday to beginning and Saturday to end
pushfirst!(day_array, "Sunday")
push!(day_array, "Saturday")

# print each element of array
println("Day of week: ")
for i in 1:length(day_array)
    println("  $(day_array[i])")
end

println("Day of the week: $(join(collect(day_array), ";"))")

# sort the array and print again
sort!(day_array)
println("Day of the week (sorted): $(join(collect(day_array), ";"))")

Output:

Length of array: 5
First day of week: Monday
Third day of week: Wednesday
Last day of week: Friday
Thursday is in ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]: true
Day of week: 
  Sunday
  Monday
  Tuesday
  Wednesday
  Thursday
  Friday
  Saturday
Day of the week: Sunday;Monday;Tuesday;Wednesday;Thursday;Friday;Saturday
Day of the week (sorted): Friday;Monday;Saturday;Sunday;Thursday;Tuesday;Wednesday

Sets

Sets are an unordered collection of unique elements.

Creating sets

ActionSyntax
New set (empty)Set[]
Specify typeSet{Int64}
Set with valuesSet([1, 2, 3, 4, 5])
Set with valuesSet(["a1", "b2", "c3", "b2"])

Interacting with sets

ActionSyntax
Get length of set my_setlength(my_set)
Check if value is in setin(str, my_set)
Add valuepush!(my_set, str)

Comparing sets

ActionSyntax
Intersectionintersect(my_set, your_set)
Unionunion(my_set, your_set)
Differencesetdiff(my_set, your_set)

Input:

# sets.jl

color_set = Set(["red", "yellow", "blue"])
color_set2 = Set(["red", "orange", "yellow"])

println("Length	of set:	$(length(color_set))")

println("Color Set 1")
for color in color_set
    println("  $(color)")
end

println("Color Set 2: $(join(collect(color_set2), "---"))")

println("Intersection: $(intersect(color_set, color_set2))")
println("Union: $(union(color_set, color_set2))")
println("Difference: $(setdiff(color_set, color_set2))")
println("Difference: $(setdiff(color_set2, color_set))")

Output:

Length	of set:	3
Color Set 1
  yellow
  blue
  red
Color Set 2: yellow---orange---red
Intersection: Set(["yellow", "red"])
Union: Set(["yellow", "orange", "blue", "red"])
Difference: Set(["blue"])
Difference: Set(["orange"])

Dictionaries

Dictionaries are unordered collection of key-value pairs where the key serves as the index (“associative collection”). Similar to elements of a set, keys are always unique.

Creating dictionaries

ActionSyntax
New dictionary (empty)Dict[]
Specify typeDict{String, Int64}
Dictionary with valuesDict("one" => 1 , "two" => 2, "three" => 3, "four" => 4)

Accessing dictionaries

ActionSyntax
Get value for key in dictionary my_dictmy_dict["one"]
Check if dictionary has keyhaskey(my_dict, "one")
Check for key/value pairin(("one" => 1), my_dict)
Get value and set defaultget!(my_dict, "one", 5)<br>get!(my_dict, "five", 5)
Add key/value pairmy_dict["five"] = 5
Delete key/value pairdelete!(my_dict, "four")
Get keyskeys(my_dict)
Get valuesvalues(dict)

Converting dictionaries

ActionSyntax
Convert keys to arraycollect(keys(my_dict))
Convert values to arraycollect(values(my_dict))

Sorting dictionaries

ActionSyntax
Sorting keyssort(collect(keys(my_dict)))
Sorting valuessort(collect(values(my_dict)))
Sort by value (descending) with keyssort(collect(zip(values(my_dict), keys(my_dict))), rev=true)
Sort by value (ascending) with keyssort(collect(zip(values(my_dict), keys(my_dict))), rev=false)
Get top n by value (e.g., 3)sort(collect(zip(values(my_dict), keys(my_dict))), rev=true)[1:3]

Input:

# dicts.jl

day_dict = Dict()
day_length_dict = Dict()

day_dict["Mon"] = "Monday"
day_dict["Tue"] = "Tuesday"
day_dict["Wed"] = "Wednesday"
day_dict["Thu"] = "Thursday"
day_dict["Fri"] = "Friday"

if haskey(day_dict, "Wed")
   println("$(day_dict["Wed"])")
end

if !haskey(day_dict, "Sat")
   println("no key \"Sat\"")
end

println("print key-value pairs")
for day in keys(day_dict)
    println("  $day = $(day_dict[day])")
end

println("print values (sorted)")
for day_value in sort(collect(values(day_dict)))
    println("  $day_value")
end

# get length of each value and keep track of lengths
for day_value in values(day_dict)
    day_length = length(day_value)
    day_length_dict[day_value] = day_length
end

println("print lengths")
for day in keys(day_length_dict)
    println("  $day = $(day_length_dict[day])")
end

println("print lengths in descending order")
for (day, length) in sort(collect(zip(values(day_length_dict), keys(day_length_dict))), rev=true)
    println("  $day = $length")
end

println("print lengths in ascending order")
for (day, length) in sort(collect(zip(values(day_length_dict), keys(day_length_dict))), rev=false)
    println("  $day = $length")
end

Output:

Wednesday
no key "Sat"
print key-value pairs
  Wed = Wednesday
  Tue = Tuesday
  Thu = Thursday
  Mon = Monday
  Fri = Friday
print values (sorted)
  Friday
  Monday
  Thursday
  Tuesday
  Wednesday
print lengths
  Friday = 6
  Tuesday = 7
  Thursday = 8
  Wednesday = 9
  Monday = 6
print lengths in descending order
  9 = Wednesday
  8 = Thursday
  7 = Tuesday
  6 = Monday
  6 = Friday
print lengths in ascending order
  6 = Friday
  6 = Monday
  7 = Tuesday
  8 = Thursday
  9 = Wednesday