Skip to content

Commit

Permalink
13. Implementing RangeSpliterator (#14)
Browse files Browse the repository at this point in the history
Co-authored-by: Alex Klymenko <[email protected]>
  • Loading branch information
alxkm and Alex Klymenko authored Jul 9, 2024
1 parent e3bf26c commit 8304112
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/main/java/org/streamer/StreamUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,53 @@ public static <T> Stream<Pair<Integer, T>> mapToIndex(Stream<T> stream) {
AtomicInteger index = new AtomicInteger(0);
return stream.map(elem -> new Pair<>(index.getAndIncrement(), elem));
}

static class RangeSpliterator implements Spliterator<Integer> {
private final int start;
private final int end;
private int current;

public RangeSpliterator(int start, int end) {
this.start = start;
this.end = end;
this.current = start;
}

@Override
public boolean tryAdvance(Consumer<? super Integer> action) {
if (current < end) {
action.accept(current++);
return true;
}
return false;
}

@Override
public Spliterator<Integer> trySplit() {
int mid = (current + end) >>> 1;
if (mid <= current) {
return null;
}
int oldCurrent = current;
current = mid;
return new RangeSpliterator(oldCurrent, mid);
}

@Override
public long estimateSize() {
return end - current;
}

@Override
public int characteristics() {
return ORDERED | SIZED | SUBSIZED | IMMUTABLE;
}
}

public static Stream<Integer> customRangeAsStream(int start, int end) {
Spliterator<Integer> spliterator = new RangeSpliterator(start, end);
return StreamSupport.stream(spliterator, false);
}
}

// Helper Pair class
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/org/streamer/StreamUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -253,4 +253,13 @@ void testMapToIndex() {
);
assertEquals(expected, result.toList());
}

@Test
public void testCustomRangeAsStream() {
int start = 1;
int end = 6;
List<Integer> expected = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = StreamUtils.customRangeAsStream(start, end).collect(Collectors.toList());
assertEquals(expected, result);
}
}

0 comments on commit 8304112

Please sign in to comment.