View Javadoc
1   package net.sf.flatpack;
2   
3   import java.util.Iterator;
4   import java.util.NoSuchElementException;
5   import java.util.Optional;
6   import java.util.Spliterator;
7   import java.util.Spliterators;
8   import java.util.stream.Stream;
9   import java.util.stream.StreamSupport;
10  
11  /**
12   * New with jdk8, define stream() methods. You should
13   * start using this BUT note that it will only return VALID Records, any invalid row will be skipped.
14   *
15   * @author Benoit Xhenseval
16   * @since 3.4
17   */
18  public interface StreamingDataSet extends RecordDataSet {
19      /**
20       * @since 4.0
21       * @return a stream of Records
22       */
23      default Stream<Record> stream() {
24          return StreamSupport
25                  .stream(Spliterators.spliteratorUnknownSize(spliterator(), Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE), false);
26      }
27  
28      /**
29       * @since 4.0
30       * @return a stream of Records
31       */
32      default Stream<Record> parallelStream() {
33          return StreamSupport
34                  .stream(Spliterators.spliteratorUnknownSize(spliterator(), Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE), true);
35      }
36  
37      default Iterator<Record> spliterator() {
38          return new Iterator<Record>() {
39              Optional<Record> nextData = Optional.empty();
40  
41              @Override
42              public boolean hasNext() {
43                  if (nextData.isPresent()) {
44                      return true;
45                  } else {
46                      if (StreamingDataSet.this.next()) {
47                          nextData = getRecord();
48                      } else {
49                          nextData = Optional.empty();
50                      }
51                      return nextData.isPresent();
52                  }
53              }
54  
55              @Override
56              public Record next() {
57                  if (nextData.isPresent() || hasNext()) {
58                      final Record line = nextData.isPresent() ? nextData.get() : null;
59                      nextData = Optional.empty();
60                      return line;
61                  } else {
62                      throw new NoSuchElementException();
63                  }
64              }
65          };
66      }
67  }