Skip to content

Commit

Permalink
Update tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
Glavo committed Jan 8, 2025
1 parent 987da66 commit c18cecb
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion docs/Tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,4 +88,49 @@ graph TD;
classDef impl fill: #4a5659, stroke: #fff, stroke-width: 4px;
class ArraySeq,MutableArray,MutableArrayList,MutableArrayDeque,MutableSmartArrayList,MutableLinkedList,MutableSinglyLinkedList,MutableEnumSet,MutableHashSet,MutableTreeSet impl;
```
```

### Creating collections using factory methods

Most collection interfaces and implementation classes provide a series of convenient static factory methods
for creating collections.

```java
// Create a collection from values
var _ = Seq.of(1, 2, 3); // ==> [1, 2, 3]

// Create a collection from array
var _ = Seq.from(new Integer[] {1, 2, 3}); // ==> [1, 2, 3]

// Create a collection from any iterable object
var _ = Seq.from(java.util.List.of(1, 2, 3)); // ==> [1, 2, 3]

// Create a collection from an iterator
var _ = Seq.from(java.util.List.of(1, 2, 3).iterator()); // ==> [1, 2, 3]

// Create a collection from a stream
var _ = Seq.from(java.util.stream.Stream.of(1, 2, 3)); // ==> [1, 2, 3]

// Create a seq filled with N identical values
var _ = Seq.fill(3, "value"); // ===> ["value", "value", "value"]

// Create a seq of N values, each of which is generated by a user-supplied function
var _ = Seq.fill(3, i -> i + 10); // ===> [10, 11, 12]

// Wrap an existing java.util.List as a Seq (without copying)
var _ = Seq.wrapJava(List.of(1, 2, 3)); // ===> [1, 2, 3]
```

In addition, each collection class/interface provides a static `factory()` method
to get a `CollectionFactory` corresponding to a collection.
The `CollectionFactory` instance also provides factory methods similar to the above and can be used as a `java.util.stream.Collector`.

```java
var _ = Seq.<Integer>factory().of(1, 2, 3); // ===> [1, 2, 3]

// Use as Collector
var _ = Stream.of(1, 2, 3).collect(Seq.factory()); // ===> [1, 2, 3]
```

More usage of `CollectionFactory` will be introduced in later chapters.

0 comments on commit c18cecb

Please sign in to comment.