Java Code Examples for java.util.stream.Stream#iterator()

The following examples show how to use java.util.stream.Stream#iterator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GraphUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
public static Rectangle getBounds(Stream<Node> nodes) {
	final Iterator<Node> i = nodes.iterator();
	if (i.hasNext()) {
		float xMin = Float.MAX_VALUE;
		float xMax = Float.MIN_VALUE;
		float yMin = Float.MAX_VALUE;
		float yMax = Float.MIN_VALUE;
		while (i.hasNext()) {
			final Node n = i.next();
			xMin = Math.min(xMin, n.getX());
			yMin = Math.min(yMin, n.getY());
			xMax = Math.max(xMax, n.getX() + n.getWidth());
			yMax = Math.max(yMax, n.getY() + n.getHeight());
		}
		return new Rectangle(xMin, yMin, xMax - xMin, yMax - yMin);
	} else
		return Rectangle.EMPTY;
}
 
Example 2
Source File: Lines.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void testIterator() throws IOException {
    MockLineReader r = new MockLineReader(6);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    assertEquals(r.getLineNumber(), 1, "Read one line");
    Stream<String> s = br.lines();
    Iterator<String> it = s.iterator();
    // Ensure iterate with only next works
    for (int i = 0; i < 5; i++) {
        String str = it.next();
        assertEquals(str, "Line " + (i + 2), "Addtional five lines");
    }
    // NoSuchElementException
    try {
        it.next();
        fail("Should have run out of lines.");
    } catch (NoSuchElementException nsse) {}
}
 
Example 3
Source File: TestColumnIndexFiltering.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
private static void assertContains(Stream<User> expected, List<User> actual) {
  Iterator<User> expIt = expected.iterator();
  if (!expIt.hasNext()) {
    return;
  }
  User exp = expIt.next();
  for (User act : actual) {
    if (act.equals(exp)) {
      if (!expIt.hasNext()) {
        break;
      }
      exp = expIt.next();
    }
  }
  assertFalse("Not all expected elements are in the actual list. E.g.: " + exp, expIt.hasNext());
}
 
Example 4
Source File: Lines.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public void testIterator() throws IOException {
    MockLineReader r = new MockLineReader(6);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    assertEquals(r.getLineNumber(), 1, "Read one line");
    Stream<String> s = br.lines();
    Iterator<String> it = s.iterator();
    // Ensure iterate with only next works
    for (int i = 0; i < 5; i++) {
        String str = it.next();
        assertEquals(str, "Line " + (i + 2), "Addtional five lines");
    }
    // NoSuchElementException
    try {
        it.next();
        fail("Should have run out of lines.");
    } catch (NoSuchElementException nsse) {}
}
 
Example 5
Source File: Lines.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void testIterator() throws IOException {
    MockLineReader r = new MockLineReader(6);
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    assertEquals(r.getLineNumber(), 1, "Read one line");
    Stream<String> s = br.lines();
    Iterator<String> it = s.iterator();
    // Ensure iterate with only next works
    for (int i = 0; i < 5; i++) {
        String str = it.next();
        assertEquals(str, "Line " + (i + 2), "Addtional five lines");
    }
    // NoSuchElementException
    try {
        it.next();
        fail("Should have run out of lines.");
    } catch (NoSuchElementException nsse) {}
}
 
Example 6
Source File: StreamDataScanner.java    From herddb with Apache License 2.0 5 votes vote down vote up
public StreamDataScanner(
        Transaction transaction, String[] fieldNames, Column[] schema,
        Stream<DataAccessor> wrapped
) {
    super(transaction, fieldNames, schema);
    this.wrapped = wrapped.iterator();
    fetchNext();
    if (transaction != null) {
        transaction.increaseRefcount();
    }
}
 
Example 7
Source File: AbstractIterableXTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test
public void headAndTailTest(){
	Stream<String> s = Stream.of("hello","world");
	Iterator<String> it = s.iterator();
	String head = it.next();
	Stream<String> tail = Streams.stream(it);
	tail.forEach(System.out::println);
}
 
Example 8
Source File: TabulatorsTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
void assertValue(List<T> value, Supplier<Stream<T>> source, boolean ordered)
        throws ReflectiveOperationException {
    if (!List.class.isAssignableFrom(value.getClass()))
        fail(String.format("Class mismatch in ListAssertion: %s", value.getClass()));
    Stream<T> stream = source.get();
    List<T> result = new ArrayList<>();
    for (Iterator<T> it = stream.iterator(); it.hasNext(); ) // avoid capturing result::add
        result.add(it.next());
    if (StreamOpFlagTestHelper.isStreamOrdered(stream) && ordered)
        assertContents(value, result);
    else
        assertContentsUnordered(value, result);
}
 
Example 9
Source File: ZipUtils.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
public static <T,U> boolean zip(final Iterable<T> ct, final Stream<U> cu, final ZipIterator<T,U> each) {
    final Iterator<T> it = ct.iterator();
    final Iterator<U> iu = cu.iterator();
    while (it.hasNext() && iu.hasNext()) {
        each.each(it.next(), iu.next());
    }
    return !it.hasNext() && !iu.hasNext();
}
 
Example 10
Source File: SkippingIterator.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static <T> Stream<T> adaptStream(Stream<T> stream, Function<? super T, ? extends DateTime> timestamp_fn, Duration stepsize) {
    if (stepsize.getMillis() <= 0L) return stream;

    final Iterator<T> iter = new SkippingIterator<>(stream.iterator(), timestamp_fn, stepsize);
    final Spliterator<T> spliter = Spliterators.spliteratorUnknownSize(iter, NONNULL | IMMUTABLE | ORDERED);
    return StreamSupport.stream(spliter, false);
}
 
Example 11
Source File: TabulatorsTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
void assertValue(Collection<T> value, Supplier<Stream<T>> source, boolean ordered)
        throws ReflectiveOperationException {
    if (!clazz.isAssignableFrom(value.getClass()))
        fail(String.format("Class mismatch in CollectionAssertion: %s, %s", clazz, value.getClass()));
    Stream<T> stream = source.get();
    Collection<T> result = clazz.newInstance();
    for (Iterator<T> it = stream.iterator(); it.hasNext(); ) // avoid capturing result::add
        result.add(it.next());
    if (StreamOpFlagTestHelper.isStreamOrdered(stream) && targetOrdered && ordered)
        assertContents(value, result);
    else
        assertContentsUnordered(value, result);
}
 
Example 12
Source File: Lines.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testInterlacedRead() throws IOException {
    MockLineReader r = new MockLineReader(10);
    BufferedReader br = new BufferedReader(r);
    char[] buf = new char[5];
    Stream<String> s = br.lines();
    Iterator<String> it = s.iterator();

    br.read(buf);
    assertEquals(new String(buf), "Line ");
    assertEquals(it.next(), "1");
    try {
        s.iterator().next();
        fail("Should failed on second attempt to get iterator from s");
    } catch (IllegalStateException ise) {}
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    // Get stream again should continue from where left
    // Only read remaining of the line
    br.lines().limit(1L).forEach(line -> assertEquals(line, "ne 2"));
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "ne");
    assertEquals(it.next(), " 3");
    // Line 4
    br.readLine();
    // interator pick
    assertEquals(it.next(), "Line 5");
    // Another stream instantiated by lines()
    AtomicInteger line_no = new AtomicInteger(6);
    br.lines().forEach(l -> assertEquals(l, "Line " + line_no.getAndIncrement()));
    // Read after EOL
    assertFalse(it.hasNext());
}
 
Example 13
Source File: Lines.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void testInterlacedRead() throws IOException {
    MockLineReader r = new MockLineReader(10);
    BufferedReader br = new BufferedReader(r);
    char[] buf = new char[5];
    Stream<String> s = br.lines();
    Iterator<String> it = s.iterator();

    br.read(buf);
    assertEquals(new String(buf), "Line ");
    assertEquals(it.next(), "1");
    try {
        s.iterator().next();
        fail("Should failed on second attempt to get iterator from s");
    } catch (IllegalStateException ise) {}
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    // Get stream again should continue from where left
    // Only read remaining of the line
    br.lines().limit(1L).forEach(line -> assertEquals(line, "ne 2"));
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "ne");
    assertEquals(it.next(), " 3");
    // Line 4
    br.readLine();
    // interator pick
    assertEquals(it.next(), "Line 5");
    // Another stream instantiated by lines()
    AtomicInteger line_no = new AtomicInteger(6);
    br.lines().forEach(l -> assertEquals(l, "Line " + line_no.getAndIncrement()));
    // Read after EOL
    assertFalse(it.hasNext());
}
 
Example 14
Source File: TabulatorsTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
void assertValue(List<T> value, Supplier<Stream<T>> source, boolean ordered)
        throws ReflectiveOperationException {
    if (!List.class.isAssignableFrom(value.getClass()))
        fail(String.format("Class mismatch in ListAssertion: %s", value.getClass()));
    Stream<T> stream = source.get();
    List<T> result = new ArrayList<>();
    for (Iterator<T> it = stream.iterator(); it.hasNext(); ) // avoid capturing result::add
        result.add(it.next());
    if (StreamOpFlagTestHelper.isStreamOrdered(stream) && ordered)
        assertContents(value, result);
    else
        assertContentsUnordered(value, result);
}
 
Example 15
Source File: BitmappedReachabilityChecker.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Check all targets are reachable from the starters.
 * <p>
 * In this implementation, it is recommended to put the most popular
 * starters (e.g. refs/heads tips) at the beginning.
 */
@Override
public Optional<RevCommit> areAllReachable(Collection<RevCommit> targets,
		Stream<RevCommit> starters) throws MissingObjectException,
		IncorrectObjectTypeException, IOException {

	List<RevCommit> remainingTargets = new ArrayList<>(targets);

	walk.reset();
	walk.sort(RevSort.TOPO);

	// Filter emits only commits that are unreachable from previously
	// visited commits. Internally it keeps a bitmap of everything
	// reachable so far, which we use to discard reachable targets.
	BitmapIndex repoBitmaps = walk.getObjectReader().getBitmapIndex();
	ReachedFilter reachedFilter = new ReachedFilter(repoBitmaps);
	walk.setRevFilter(reachedFilter);

	Iterator<RevCommit> startersIter = starters.iterator();
	while (startersIter.hasNext()) {
		walk.markStart(startersIter.next());
		while (walk.next() != null) {
			remainingTargets.removeIf(reachedFilter::isReachable);

			if (remainingTargets.isEmpty()) {
				return Optional.empty();
			}
		}
		walk.reset();
	}

	return Optional.of(remainingTargets.get(0));
}
 
Example 16
Source File: Lines.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testInterlacedRead() throws IOException {
    MockLineReader r = new MockLineReader(10);
    BufferedReader br = new BufferedReader(r);
    char[] buf = new char[5];
    Stream<String> s = br.lines();
    Iterator<String> it = s.iterator();

    br.read(buf);
    assertEquals(new String(buf), "Line ");
    assertEquals(it.next(), "1");
    try {
        s.iterator().next();
        fail("Should failed on second attempt to get iterator from s");
    } catch (IllegalStateException ise) {}
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    // Get stream again should continue from where left
    // Only read remaining of the line
    br.lines().limit(1L).forEach(line -> assertEquals(line, "ne 2"));
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "Li");
    br.read(buf, 0, 2);
    assertEquals(new String(buf, 0, 2), "ne");
    assertEquals(it.next(), " 3");
    // Line 4
    br.readLine();
    // interator pick
    assertEquals(it.next(), "Line 5");
    // Another stream instantiated by lines()
    AtomicInteger line_no = new AtomicInteger(6);
    br.lines().forEach(l -> assertEquals(l, "Line " + line_no.getAndIncrement()));
    // Read after EOL
    assertFalse(it.hasNext());
}
 
Example 17
Source File: Parser.java    From funcj with MIT License 5 votes vote down vote up
/**
 * Variation of {@link Parser#sequence(IList)} for {@link Stream}.
 * @param spt       the stream of {@code Parser} values
 * @param <E>       the error type
 * @param <T>       the value type of the {@code Parser}s in the stream
 * @return          a {@code Parser} which wraps an {@link Stream} of values
 */
static <E, T> Parser<E, Stream<T>> sequence(Stream<Parser<E, T>> spt) {
    final Iterator<Parser<E, T>> iter = spt.iterator();
    Parser<E, IList<T>> plt = pure(IList.empty());
    while (iter.hasNext()) {
        final Parser<E, T> pt = iter.next();
        plt = ap(plt.map(lt -> lt::add), pt);
    }
    return plt.map(IList::stream);
}
 
Example 18
Source File: CloseableRemoteIterator.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
CloseableRemoteIterator(Stream<T> stream) {
  this.stream = stream;
  this.iterator = stream.iterator();
}
 
Example 19
Source File: FoldsGenEx.java    From funcj with MIT License 3 votes vote down vote up
/**
 * Left-fold a function over a {@link Stream}.
 * @param f         the binary function to be applied for the fold
 * @param z         the starting value for the fold
 * @param str       the stream to be folded over
 * @param <T>       the stream element type
 * @param <R>       the result type of fold operation
 * @param <X>       the exception type
 * @return          the folded value
 * @throws X        the exception thrown by the function
 */
public static <T, R, X extends Exception> R foldLeft(F2<R, T, R, X> f, R z, Stream<T> str) throws X {
    R acc = z;
    for (Iterator<T> iter = str.iterator(); iter.hasNext();) {
        acc = f.apply(acc, iter.next());
    }
    return acc;
}
 
Example 20
Source File: OrderedStreamUtils.java    From stream-utils with Apache License 2.0 3 votes vote down vote up
/**
 * Java 8 streams don't support streaming groupings, just materialized grouping.
 * This groups a stream by a key, using the keying function provided.
 *
 * The stream must be sorted by the key for this to function properly.
 *
 * Note - when you use this operator, you need to be aware that you are relinquishing
 * ALL control of the base stream. Do NOT try to reuse the inputted stream. Do NOT
 * try to close the underlying stream. All interactions must now be done with the
 * stream you get in return.
 *
 * @param stream stream to group.
 * @param keyingFunction function to generate the key to be grouped by.
 * @return grouped stream.
 */
public static <TYPE, KEY> Stream<List<TYPE>> groupBy(Stream<TYPE> stream, Function<TYPE, KEY> keyingFunction) {
    final Iterator<TYPE> iterator = stream.iterator();

    final Iterator<List<TYPE>> iter = new KeyedBufferIterator<>(iterator, keyingFunction);

    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, 0), false)
            // Whenever the grouped stream is closed, we need to close the
            // underlying stream.
            .onClose(stream::close);
}