# Arrays, lists, and iterators

> Select collections and transform, filter, reduce, group, sort, and combine their elements.

Canonical: https://alice-lang.org/documentation/library/collections/

[Documentation index](https://alice-lang.org/documentation/llms.txt) · [Complete book](https://alice-lang.org/llms-full.txt)

## Choose a collection

An array literal such as `[1, 2, 3]` is a fixed-size .NET array. Use `Array(T).new(length)` for a typed array of a chosen size. Use `List(T).new` for a growable collection; `.Add(value)` or `<<` appends.

```alice
items = List(String).new
items.Add("tea")
items << "cake"
puts items.size
```

Do not assume an array grows when you append. The underlying storage and available .NET operations still matter.

## Transform, filter, and reduce

```alice
numbers = [3, 1, 4, 1, 5]
puts numbers.select { |n| n > 2 }.sort.join(",")
puts numbers.map { |n| n * 2 }.sum
puts numbers.uniq.size
```

Expected output:

```text
3,4,5
28
4
```

[Edit and run in the Alice playground](https://playground.alice-lang.org/#code=u.bnVtYmVycyA9IFszLCAxLCA0LCAxLCA1XQpwdXRzIG51bWJlcnMuc2VsZWN0IHsgfG58IG4gPiAyIH0uc29ydC5qb2luKCIsIikKcHV0cyBudW1iZXJzLm1hcCB7IHxufCBuICogMiB9LnN1bQpwdXRzIG51bWJlcnMudW5pcS5zaXpl)

`map` transforms each value, `select` keeps values whose predicate is true, and `sum` reduces values to a number. `reject` keeps values whose predicate is false. The original array is not sorted in place by `sort`; the helper returns a sorted array.

| Operation                          | Behavior                                                   |
| ---------------------------------- | ---------------------------------------------------------- |
| `each { \|x\| ... }`               | Visit elements for effects                                 |
| `each_with_index { \|x, i\| ... }` | Visit with a zero-based index                              |
| `map { \|x\| ... }`                | Produce transformed elements                               |
| `select`, `reject`                 | Keep or reject predicate matches                           |
| `find { \|x\| ... }`               | Find the first match; account for a missing/default result |
| `find_index { \|x\| ... }`         | Find a matching position                                   |
| `any?`, `all?`                     | Test whether any/all elements satisfy a predicate          |
| `count`, `count { \|x\| ... }`     | Number of elements or matches                              |
| `sum`, `sum { \|x\| ... }`         | Sum values or mapped values                                |
| `reduce(seed) { \|acc, x\| ... }`  | Fold into an accumulator                                   |
| `inject`                           | Reduction alias                                            |

Prefer a seed for reductions that can receive empty input. Operations such as `first`, `last`, `min`, `max`, and unseeded reduction may throw on an empty sequence; check emptiness when it is a valid input.

## Select portions and inspect

| Methods                                | Purpose                         |
| -------------------------------------- | ------------------------------- |
| `size`, `length`, `empty?`             | Size and emptiness              |
| `first`, `last`, `first(n)`, `last(n)` | Endpoints or endpoint slices    |
| `take(n)`, `drop(n)`                   | Prefix or remainder             |
| `take_while`, `drop_while`             | Predicate-based prefix handling |
| `include?(value)`                      | Membership                      |
| `each_slice(n)`, `each_cons(n)`        | Batches or sliding windows      |
| `reverse`, `reverse_each`              | Reversed data or traversal      |
| `to_a`, `to_list`                      | Materialize an array or list    |
| `join(separator)`                      | Convert elements to joined text |

Methods consuming `IEnumerable(T)` may enumerate it. Repeated calls can repeat work or effects on a non-array source.

## Ordering and grouping

`sort` uses the element's ordering; `sort { |a, b| ... }` supplies a comparison. `sort_by { |x| key }` orders by a derived key. `min_by` and `max_by` choose an element by its key; `minmax` returns both extrema.

`uniq` removes duplicates; its block form chooses the uniqueness key. `group_by` produces key-to-group data, `partition` splits matches from nonmatches, and `tally` counts repeated elements. `chunk_while` groups adjacent elements while its condition holds.

```alice
puts ["tea", "cake", "jam"].sort_by { |s| s.size }.join(",")
```

## Combine and enumerate combinations

`zip` combines corresponding positions, `flatten` flattens nested collections, `flat_map` maps then flattens, and `compact` removes absent entries in supported nullable collections. `product`, `combination(k)`, and `permutation(k)` enumerate combinations; their result sizes can grow rapidly.

`shuffle`, `sample`, and `rotate` rearrange or choose data. Randomized operations can take a `Random` where supported; provide one with a fixed seed for repeatable tests. `cycle(n)` repeats traversal, `step(n)` visits a stride, and `each_with_object` carries an explicit object through traversal.

## Allocation and execution

A literal block chain ending in a sink can compile into one loop, sometimes with SIMD or parallel work. A stored intermediate collection still needs storage. Impure blocks remain serial when purity cannot be established. See [performance](https://alice-lang.org/documentation/guides/performance.md) for the exact model rather than treating every collection helper as lazy or allocation-free.

## Continue reading

- Previous: [Tuples, delegates, and reflection](https://alice-lang.org/documentation/language/tuples.md)
- Next: [Hashes and dictionaries](https://alice-lang.org/documentation/library/hashes.md)
