Skip to content

Clojure 1.12 consuming Java streams (interop) #83

Open
@seancorfield

Description

@seancorfield

From the release notes:

Java APIs increasingly return Streams and are hard to consume because they do not implement interfaces that Clojure already supports, and hard to interop with because Clojure doesn't directly implement Java functional interfaces.

In addition to functional interface support, Clojure now provides these functions to interoperate with streams in an idiomatic manner, all functions behave analogously to their Clojure counterparts:

(stream-seq! stream) => seq
(stream-reduce! f [init-val] stream) => val
(stream-transduce! xf f [init-val] stream) => val
(stream-into! to-coll [xf] stream) => to-coll

All of these operations are terminal stream operations (they consume the stream).

See: CLJ-2775

Activity

self-assigned this
on Jan 1, 2025
seancorfield

seancorfield commented on Jan 1, 2025

@seancorfield
ContributorAuthor

Official docs to link to https://clojure.org/reference/java_interop#streams (identical to what's in the release notes -- so we need examples!).

seancorfield

seancorfield commented on Jan 1, 2025

@seancorfield
ContributorAuthor
user=> (java.nio.file.Path/of "deps.edn" (into-array String []))
#object[sun.nio.fs.UnixPath 0x366665c5 "deps.edn"]
user=> (java.nio.file.Files/lines *1)
#object[java.util.stream.ReferencePipeline$Head 0x684e651f "java.util.stream.ReferencePipeline$Head@684e651f"]
user=> (stream-into! [] *1)
seancorfield

seancorfield commented on Feb 23, 2025

@seancorfield
ContributorAuthor

Unconvincing example with future as Supplier 😄

user=> (stream-into! [] (take 5) (java.util.stream.Stream/generate (future 42)))
[42 42 42 42 42]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

    Development

    No branches or pull requests

      Participants

      @seancorfield

      Issue actions

        Clojure 1.12 consuming Java streams (interop) · Issue #83 · clojure-doc/clojure-doc.github.io