diff --git a/docs/Tutorial.md b/docs/Tutorial.md index 48671a4e..db8efee5 100644 --- a/docs/Tutorial.md +++ b/docs/Tutorial.md @@ -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; -``` \ No newline at end of file +``` + +### 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.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. +