3
(import java.nio.file.Files)
(import java.nio.file.Paths)
(import java.util.stream.Stream)

(def path 
  (Paths/get "." 
    (into-array ["data" "10000000.test.log"])))

(def stream 
  (Files/lines path))

This way I have:

stream
#object[java.util.stream.ReferencePipeline$Head 0x50129b8f
"java.util.stream.ReferencePipeline$Head@50129b8f"]

Is there a way to iterate over this without running out of memory? The suggestion on SO are not really helpful. The files is ~1G.

3 Answers 3

6

Do the same thing you would do in java. Call interop methods on it, like (.map stream ...), or whatever else, and collect it to a list at the end, or reduce it, or whatever you need to do.

Clojure functions don't implement the interfaces that a stream expects, such as java.util.function.Function, so you'll need to use reify instead of a simple fn:

(.map stream (reify java.util.function.Function
               (apply [this x]
                 (foo x))))
Sign up to request clarification or add additional context in comments.

3 Comments

Not sure how this supposed to work. (def test (.map stream (reify java.util.function.Function (apply [this x] (println x))))) (take 1 test) Error printing return value (IllegalArgumentException) at clojure.lang.RT/seqFrom (RT.java:557). Don't know how to create ISeq from: java.util.stream.ReferencePipeline$3
A java stream is not a clojure sequence, and so you can't call clojure sequence functions on it. This is as true of (.map stream f) as it is of just stream.
Note: (apply …) above is not apply but the java.util.function.Function method apply. This may be obvious to others but it tripped me up for a hot second here.
2

You may want to look into a library called ike.cljj for some interop niceties.

Comments

1

I wanted to iterate over the stream Java / imperative style to avoid blowing up the heap. I do not need to reduce on the stream, I need to process every line and take out one field and send it out. I think for this I probably better off with doseq.

(doseq 
  [l (iterator-seq (.iterator stream))] 
    (println l))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.