Converting lists, arrays, and sets

To convert arrays, lists, and sets to other types, use the following enhancement methods:

  • Call the toArray method to convert a Set or a List to an Array.
  • Call the toList method to convert a Set or an Array to a List.
  • Call the toSet method to convert a List or an Array to a Set.
  • Call the join method to combine the elements of an Array, a List, or a Set into a String, separated by a delimiter that you specify. For example, the following line combines all the items in the array into a String, separated by commas:
    joinedString = array.join(",")

Converting an array or a list to a set removes duplicate values.

The following code shows the effects of various conversions:

// Declare and initialize an array list of strings.
var myStrings = new ArrayList<String>(){"a", "b", "bb", "ab", "abc", "abcd"}

// Create a new array list with the lenghts of the strings.
var lengthsOnly : List<Integer> as ArrayList = myStrings.map(\ str:String -> str.length)
var lengthsSet = lengthsOnly.toSet()
var lengthsArray = lengthsOnly.toArray()
var lengthsStr = lengthsOnly.join("|")
print(typeof lengthsOnly + " " + lengthsOnly.size() + " " + lengthsOnly)
print(typeof lengthsSet + " " + lengthsSet.size() + " " + lengthsSet)
print(typeof lengthsArray + " " + lengthsArray.length)
print(lengthsStr)

This code prints the following lines:

java.util.ArrayList<java.lang.Object> 6 [1, 1, 2, 2, 3, 4]
java.util.HashSet<java.lang.Object> 4 [1, 2, 3, 4]
java.lang.Object[] 6
1|1|2|2|3|4