1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.spf4j.base;
17
18 import edu.umd.cs.findbugs.annotations.CleanupObligation;
19 import edu.umd.cs.findbugs.annotations.DischargesObligation;
20 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.io.Closeable;
22 import java.util.Iterator;
23 import java.util.stream.Stream;
24 import java.util.stream.StreamSupport;
25
26
27
28
29
30 @CleanupObligation
31 public interface CloseableIterable<T> extends Closeable, Iterable<T> {
32
33 @DischargesObligation
34 void close();
35
36 static <T> CloseableIterable<T> from(final CloseableIterator<T> iterator) {
37 return new CloseableIterable<T>() {
38 @Override
39 public void close() {
40 iterator.close();
41 }
42
43 @Override
44 public Iterator<T> iterator() {
45 return iterator;
46 }
47
48 };
49 }
50
51 static <T> CloseableIterable<T> from(final Iterable<T> it) {
52 return from(it, () -> { });
53 }
54
55
56 static <T> CloseableIterable<T> from(final Iterable<T> it, final AutoCloseable close) {
57 return new CloseableIterable<T>() {
58 @Override
59 @SuppressFBWarnings("EXS_EXCEPTION_SOFTENING_NO_CHECKED")
60 public void close() {
61 try {
62 close.close();
63 } catch (RuntimeException | Error e) {
64 throw e;
65 } catch (Exception ex) {
66 throw new RuntimeException(ex);
67 }
68 }
69
70 @Override
71 public Iterator<T> iterator() {
72 return it.iterator();
73 }
74 };
75 }
76
77 default Stream<T> toStream() {
78 return toStream(false);
79 }
80
81 default Stream<T> toStream(final boolean parallel) {
82 return StreamSupport.stream(spliterator(), parallel).onClose(() -> this.close());
83 }
84
85 }