You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2020/10/18 09:39:58 UTC

[groovy] 01/01: GROOVY-8258: Reuse the stream as possible as we could

This is an automated email from the ASF dual-hosted git repository.

sunlan pushed a commit to branch GROOVY-8258
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit 475c349d9bceddd0850c54050633970f2bda091a
Author: Daniel Sun <su...@apache.org>
AuthorDate: Sun Oct 18 17:33:48 2020 +0800

    GROOVY-8258: Reuse the stream as possible as we could
---
 .../linq/provider/collection/QueryableCollection.java      | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)

diff --git a/subprojects/groovy-linq/src/main/groovy/org/apache/groovy/linq/provider/collection/QueryableCollection.java b/subprojects/groovy-linq/src/main/groovy/org/apache/groovy/linq/provider/collection/QueryableCollection.java
index 476c0d3..61997ce 100644
--- a/subprojects/groovy-linq/src/main/groovy/org/apache/groovy/linq/provider/collection/QueryableCollection.java
+++ b/subprojects/groovy-linq/src/main/groovy/org/apache/groovy/linq/provider/collection/QueryableCollection.java
@@ -45,6 +45,7 @@ import static org.apache.groovy.linq.provider.collection.Queryable.from;
 @Internal
 class QueryableCollection<T> implements Queryable<T>, Iterable<T> {
     private final Iterable<T> sourceIterable;
+    private Stream<T> sourceStream;
 
     QueryableCollection(Iterable<T> sourceIterable) {
         if (sourceIterable instanceof QueryableCollection) {
@@ -199,7 +200,18 @@ class QueryableCollection<T> implements Queryable<T>, Iterable<T> {
 
     @Override
     public Stream<T> stream() {
-        return toStream(sourceIterable);  // we have to create new stream every time because Java stream can not be reused
+        if (null != sourceStream) {
+            try {
+                sourceStream.peek(e -> {}); // check if the stream is usable
+                return sourceStream;
+            } catch (IllegalStateException ignore) {
+            }
+        }
+
+        // we have to create new stream because Java stream can not be reused
+        sourceStream = toStream(sourceIterable);
+
+        return sourceStream;
     }
 
     @Override