Grouping

Syntax

	$list.groupBy($key-fun)

$list.groupBy($key-fun, $map-fun)

Description

Groups a list by key values calculated by a key function. If a mapping function is specified, it will be executed on each group afterwards.

The values of the list are filtered according to the key function and stored in a dictionary. If you are only interested in a certain key value, a simple filtering is sufficient. One uses a grouping only if the grouping result is used several times, i.e. many keys are accessed.

Parameter

Name Type Description Mandatory Default
list Set A list to be grouped. yes
key-fun Function Key function that determines a key value for a value from list. The key value determines the group into which the value from list is sorted. yes
map-fun Function Mapping function which is applied to each created value group. no No mapping function will be executed

Return value

Type: Business object

A dictionary containing a list of associated elements from list for each calculated key value.

Examples

Grouping of names by first letter

list("Joe", "Tom", "Jane", "Tylor", "Erik")
  .groupBy(name -> $name.subString(0, 1))

Output: A dictionary with the following values:

{
  "J": ["Joe", "Jane"], 
  "T": ["Tom", "Tylor"],
  "E": ["Erik"]
}

A list of names is to be grouped by initial letter. The input list contains the strings "Joe", "Tom", "Jane", "Tylor", and "Erik". The grouping function name -> $name.subString(0, 1) assigns each name to its initial letter. The result is a dictionary that lists under an initial letter all the names in the input list that begin with that letter.

Access to groupings

{
  myGroup = 
    list("Joe", "Tom", "Jane", "Tylor", "Erik")
      .groupBy(name -> $name.subString(0, 1));
  $myGroup["J"];
}

Output: A list with the values ["Joe", "Jane"].

Since a grouping has a dictionary as its result, access is made accordingly. The above expression evaluates to the list of those names that begin with the letter "J" ("Joe", "Jane"):

Alternatively, a simple filtering can be performed here:

list("Joe", "Tom", "Jane", "Tylor", "Erik")
  .filter(name -> $name.subString(0, 1) == "J")

Grouping with mapping function

list(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  .groupBy(number -> $number % 2, number -> $number / 2)

Output: A dictionary with the following values:

{
  1.0: [0.5, 1.5, 2.5, 3.5, 4.5], 
  0.0: [1.0, 2.0, 3.0, 4.0, 5.0]
}

The function first groups all numbers in the list by even and odd numbers. Then these are divided by 2.