java.util.function.IntConsumer Java Examples

The following examples show how to use java.util.function.IntConsumer. 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: IntPipeline.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final IntStream peek(IntConsumer action) {
    Objects.requireNonNull(action);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    0) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    action.accept(t);
                    downstream.accept(t);
                }
            };
        }
    };
}
 
Example #2
Source File: ReversingIntArraySpliterator.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Override
public void forEachRemaining(IntConsumer action) {
    Objects.requireNonNull(action);

    int index = this.index; //local index for replayability

    if (!reverse) {
        for (;index < max && index > -1;) {
            action.accept(array[index++]);

        }
    } else {
        for (;index > (start-1) & index < max;) {
            action.accept(array[index--]);

        }
    }
}
 
Example #3
Source File: SpinedBufferTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "IntSpinedBuffer", groups = { "serialization-hostile" })
public void testIntLastSplit(int[] array, SpinedBuffer.OfInt sb) {
    Spliterator.OfInt spliterator = sb.spliterator();
    Spliterator.OfInt split = spliterator.trySplit();
    long splitSizes = (split == null) ? 0 : split.getExactSizeIfKnown();
    long lastSplitSize = spliterator.getExactSizeIfKnown();
    splitSizes += lastSplitSize;

    assertEquals(splitSizes, array.length);

    List<Integer> contentOfLastSplit = new ArrayList<>();
    spliterator.forEachRemaining((IntConsumer) contentOfLastSplit::add);

    assertEquals(contentOfLastSplit.size(), lastSplitSize);

    List<Integer> end = Arrays.stream(array)
            .boxed()
            .skip(array.length - lastSplitSize)
            .collect(Collectors.toList());
    assertEquals(contentOfLastSplit, end);
}
 
Example #4
Source File: NodeBuilderTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "Node.Builder<Integer>", groups = { "serialization-hostile" })
public void testIntIteration(List<Integer> l, Function<Integer, Node.Builder.OfInt> m) {
    Node.Builder.OfInt nb = m.apply(l.size());
    nb.begin(l.size());
    for (Integer i : l) {
        nb.accept((int) i);
    }
    nb.end();

    Node.OfInt n = nb.build();
    assertEquals(n.count(), l.size());

    {
        List<Integer> _l = new ArrayList<>();
        n.forEach((IntConsumer) _l::add);

        assertContents(_l, l);
    }

}
 
Example #5
Source File: MarkFile.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Map a pre-existing {@link MarkFile} if one present and is active.
 *
 * Total length of {@link MarkFile} will be mapped until {@link #close()} is called.
 *
 * @param directory            for the {@link MarkFile} file.
 * @param filename             of the {@link MarkFile} file.
 * @param versionFieldOffset   to use for version field access.
 * @param timestampFieldOffset to use for timestamp field access.
 * @param timeoutMs            for the activity check (in milliseconds) and for how long to wait for file to exist.
 * @param epochClock           to use for time checks.
 * @param versionCheck         to use for existing {@link MarkFile} file and version field.
 * @param logger               to use to signal progress or null.
 */
public MarkFile(
    final File directory,
    final String filename,
    final int versionFieldOffset,
    final int timestampFieldOffset,
    final long timeoutMs,
    final EpochClock epochClock,
    final IntConsumer versionCheck,
    final Consumer<String> logger)
{
    validateOffsets(versionFieldOffset, timestampFieldOffset);

    this.parentDir = directory;
    this.markFile = new File(directory, filename);
    this.mappedBuffer = mapExistingMarkFile(
        markFile, versionFieldOffset, timestampFieldOffset, timeoutMs, epochClock, versionCheck, logger);
    this.buffer = new UnsafeBuffer(mappedBuffer);
    this.versionFieldOffset = versionFieldOffset;
    this.timestampFieldOffset = timestampFieldOffset;
}
 
Example #6
Source File: Streams.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
@HotSpotIntrinsicCandidate
public void forEachRemaining(IntConsumer consumer) {
    Objects.requireNonNull(consumer);

    int i = from;
    final int hUpTo = upTo;
    int hLast = last;
    from = upTo;
    last = 0;
    while (i < hUpTo) {
        consumer.accept(i++);
    }
    if (hLast > 0) {
        // Last element of closed range
        consumer.accept(i);
    }
}
 
Example #7
Source File: Streams.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public boolean tryAdvance(IntConsumer consumer) {
    Objects.requireNonNull(consumer);

    final int i = from;
    if (i < upTo) {
        from++;
        consumer.accept(i);
        return true;
    }
    else if (last > 0) {
        last = 0;
        consumer.accept(i);
        return true;
    }
    return false;
}
 
Example #8
Source File: NodeBuilderTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "Node.Builder<Integer>", groups = { "serialization-hostile" })
public void testIntIteration(List<Integer> l, Function<Integer, Node.Builder.OfInt> m) {
    Node.Builder.OfInt nb = m.apply(l.size());
    nb.begin(l.size());
    for (Integer i : l) {
        nb.accept((int) i);
    }
    nb.end();

    Node.OfInt n = nb.build();
    assertEquals(n.count(), l.size());

    {
        List<Integer> _l = new ArrayList<>();
        n.forEach((IntConsumer) _l::add);

        assertContents(_l, l);
    }

}
 
Example #9
Source File: HybridBatchLearner.java    From amr with GNU General Public License v2.0 6 votes vote down vote up
public HybridBatchLearner(int numIterations,
		IDataCollection<LabeledAmrSentence> trainingData, boolean sortData,
		int maxSentenceLength, GraphAmrParser parser,
		IJointOutputLogger<LogicalExpression, LogicalExpression, LogicalExpression> parserOutputLogger,
		ICategoryServices<LogicalExpression> categoryServices,
		ILexiconGeneratorPrecise<LabeledAmrSentence, LogicalExpression, IJointModelImmutable<SituatedSentence<AMRMeta>, LogicalExpression, LogicalExpression>> genlex,
		IJointInferenceFilterFactory<LabeledAmrSentence, LogicalExpression, LogicalExpression, LogicalExpression> filterFactory,
		IntConsumer postIteration, boolean pruneLexicon,
		BiFunction<Predicate<LexicalEntry<LogicalExpression>>, Map<LexicalEntry<LogicalExpression>, Double>, Set<LexicalEntry<LogicalExpression>>> votingProcedure,
		IWeightUpdateProcedure estimator,
		IGradientFunction gradientFunction,
		Integer conditionedInferenceBeam,
		ILexiconGenerator<LabeledAmrSentence, LogicalExpression, IJointModelImmutable<SituatedSentence<AMRMeta>, LogicalExpression, LogicalExpression>> alignmentGenlex,
		boolean resumedLearning,
		ILexiconImmutable<LogicalExpression> entriesNotToPrune) {
	super(numIterations, trainingData, sortData, maxSentenceLength, parser,
			parserOutputLogger, categoryServices, genlex, filterFactory,
			postIteration, pruneLexicon, votingProcedure, estimator,
			gradientFunction, conditionedInferenceBeam, alignmentGenlex,
			resumedLearning, entriesNotToPrune);
}
 
Example #10
Source File: IntPipeline.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public final IntStream peek(IntConsumer action) {
    Objects.requireNonNull(action);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    0) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    action.accept(t);
                    downstream.accept(t);
                }
            };
        }
    };
}
 
Example #11
Source File: IntPipeline.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public final IntStream peek(IntConsumer action) {
    Objects.requireNonNull(action);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    0) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    action.accept(t);
                    downstream.accept(t);
                }
            };
        }
    };
}
 
Example #12
Source File: Streams.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean tryAdvance(IntConsumer consumer) {
    Objects.requireNonNull(consumer);

    final int i = from;
    if (i < upTo) {
        from++;
        consumer.accept(i);
        return true;
    }
    else if (last > 0) {
        last = 0;
        consumer.accept(i);
        return true;
    }
    return false;
}
 
Example #13
Source File: Spliterators.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override
public boolean tryAdvance(IntConsumer action) {
    if (action == null)
        throw new NullPointerException();
    if (index >= 0 && index < fence) {
        action.accept(array[index++]);
        return true;
    }
    return false;
}
 
Example #14
Source File: PrimitiveIterator.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @implSpec
 * If the action is an instance of {@code IntConsumer} then it is cast
 * to {@code IntConsumer} and passed to {@link #forEachRemaining};
 * otherwise the action is adapted to an instance of
 * {@code IntConsumer}, by boxing the argument of {@code IntConsumer},
 * and then passed to {@link #forEachRemaining}.
 */
@Override
default void forEachRemaining(Consumer<? super Integer> action) {
    if (action instanceof IntConsumer) {
        forEachRemaining((IntConsumer) action);
    }
    else {
        // The method reference action::accept is never null
        Objects.requireNonNull(action);
        if (Tripwire.ENABLED)
            Tripwire.trip(getClass(), "{0} calling PrimitiveIterator.OfInt.forEachRemainingInt(action::accept)");
        forEachRemaining((IntConsumer) action::accept);
    }
}
 
Example #15
Source File: Spliterators.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an {@code PrimitiveIterator.OfInt} from a
 * {@code Spliterator.OfInt}.
 *
 * <p>Traversal of elements should be accomplished through the iterator.
 * The behaviour of traversal is undefined if the spliterator is operated
 * after the iterator is returned.
 *
 * @param spliterator The spliterator
 * @return An iterator
 * @throws NullPointerException if the given spliterator is {@code null}
 */
public static PrimitiveIterator.OfInt iterator(Spliterator.OfInt spliterator) {
    Objects.requireNonNull(spliterator);
    class Adapter implements PrimitiveIterator.OfInt, IntConsumer {
        boolean valueReady = false;
        int nextElement;

        @Override
        public void accept(int t) {
            valueReady = true;
            nextElement = t;
        }

        @Override
        public boolean hasNext() {
            if (!valueReady)
                spliterator.tryAdvance(this);
            return valueReady;
        }

        @Override
        public int nextInt() {
            if (!valueReady && !hasNext())
                throw new NoSuchElementException();
            else {
                valueReady = false;
                return nextElement;
            }
        }
    }

    return new Adapter();
}
 
Example #16
Source File: ReferencePipeline.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final IntStream flatMapToInt(Function<? super P_OUT, ? extends IntStream> mapper) {
    Objects.requireNonNull(mapper);
    // We can do better than this, by polling cancellationRequested when stream is infinite
    return new IntPipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                          StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedReference<P_OUT, Integer>(sink) {
                IntConsumer downstreamAsInt = downstream::accept;
                @Override
                public void begin(long size) {
                    downstream.begin(-1);
                }

                @Override
                public void accept(P_OUT u) {
                    try (IntStream result = mapper.apply(u)) {
                        // We can do better that this too; optimize for depth=0 case and just grab spliterator and forEach it
                        if (result != null)
                            result.sequential().forEach(downstreamAsInt);
                    }
                }
            };
        }
    };
}
 
Example #17
Source File: Streams.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void forEachRemaining(IntConsumer action) {
    Objects.requireNonNull(action);

    if (count == -2) {
        action.accept(first);
        count = -1;
    }
}
 
Example #18
Source File: StreamSpliterators.java    From desugar_jdk_libs with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean tryAdvance(IntConsumer action) {
    Objects.requireNonNull(action);

    action.accept(s.getAsInt());
    return true;
}
 
Example #19
Source File: Streams.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override
public void forEachRemaining(IntConsumer action) {
    Objects.requireNonNull(action);

    if (count == -2) {
        action.accept(first);
        count = -1;
    }
}
 
Example #20
Source File: Spliterator.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @implSpec
 * If the action is an instance of {@code IntConsumer} then it is cast
 * to {@code IntConsumer} and passed to
 * {@link #tryAdvance(java.util.function.IntConsumer)}; otherwise
 * the action is adapted to an instance of {@code IntConsumer}, by
 * boxing the argument of {@code IntConsumer}, and then passed to
 * {@link #tryAdvance(java.util.function.IntConsumer)}.
 */
@Override
default boolean tryAdvance(Consumer<? super Integer> action) {
    if (action instanceof IntConsumer) {
        return tryAdvance((IntConsumer) action);
    }
    else {
        if (Tripwire.ENABLED)
            Tripwire.trip(getClass(),
                          "{0} calling Spliterator.OfInt.tryAdvance((IntConsumer) action::accept)");
        return tryAdvance((IntConsumer) action::accept);
    }
}
 
Example #21
Source File: RegisterParams.java    From teku with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public RegisterParams(
    final CommandSpec commandSpec,
    final Eth1PrivateKeyOptions eth1PrivateKeyOptions,
    final IntConsumer shutdownFunction,
    final ConsoleAdapter consoleAdapter) {
  this.spec = commandSpec;
  this.eth1PrivateKeyOptions = eth1PrivateKeyOptions;
  this.shutdownFunction = shutdownFunction;
  this.consoleAdapter = consoleAdapter;
}
 
Example #22
Source File: Node.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
default Node.OfInt truncate(long from, long to, IntFunction<Integer[]> generator) {
    if (from == 0 && to == count())
        return this;
    long size = to - from;
    Spliterator.OfInt spliterator = spliterator();
    Node.Builder.OfInt nodeBuilder = Nodes.intBuilder(size);
    nodeBuilder.begin(size);
    for (int i = 0; i < from && spliterator.tryAdvance((IntConsumer) e -> { }); i++) { }
    for (int i = 0; (i < size) && spliterator.tryAdvance((IntConsumer) nodeBuilder); i++) { }
    nodeBuilder.end();
    return nodeBuilder.build();
}
 
Example #23
Source File: Random.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void forEachRemaining(IntConsumer consumer) {
    if (consumer == null) throw new NullPointerException();
    long i = index, f = fence;
    if (i < f) {
        index = f;
        Random r = rng;
        int o = origin, b = bound;
        do {
            consumer.accept(r.internalNextInt(o, b));
        } while (++i < f);
    }
}
 
Example #24
Source File: HandleExceptionTest.java    From JavaBase with MIT License 5 votes vote down vote up
@Test(expected = NullPointerException.class)
public void testException() {
  IntConsumer consumer = v -> {
    if (v > 3) {
      throw new NullPointerException("Oops " + v);
    } else {
      System.out.println(v);
    }
  };

  IntStream.rangeClosed(1, 5).forEach(consumer);
}
 
Example #25
Source File: Streams.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void forEachRemaining(IntConsumer action) {
    Objects.requireNonNull(action);

    if (count == -2) {
        action.accept(first);
        count = -1;
    }
}
 
Example #26
Source File: SpinedBuffer.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
@Override
public void forEach(Consumer<? super Integer> consumer) {
    if (consumer instanceof IntConsumer) {
        forEach((IntConsumer) consumer);
    }
    else {
        if (Tripwire.ENABLED)
            Tripwire.trip(getClass(), "{0} calling SpinedBuffer.OfInt.forEach(Consumer)");
        spliterator().forEachRemaining(consumer);
    }
}
 
Example #27
Source File: IntPipeline.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void forEach(IntConsumer action) {
    if (!isParallel()) {
        adapt(sourceStageSpliterator()).forEachRemaining(action);
    }
    else {
        super.forEach(action);
    }
}
 
Example #28
Source File: SimulationFeeder.java    From Shuffle-Move with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Fills each column for the specified simFeeder to a minimum height as specified. The blocks
 * used will be randomly chosen from the given ArrayList.
 * 
 * @param simFeeder
 * @param minHeight
 * @param possibleBlocks
 * @return
 */
private static SimulationFeeder fillToLevel(SimulationFeeder simFeeder, int minHeight,
      ArrayList<Species> possibleBlocks) {
   SimulationFeeder ret = new SimulationFeeder(simFeeder);
   if (minHeight == 0 || possibleBlocks.isEmpty()) {
      return ret;
   }
   // Using IntStream from random to streamline the performance a little bit.
   int[] numToAdd = new int[Board.NUM_COLS];
   int sum = 0;
   for (int i = 1; i <= Board.NUM_COLS; i++) {
      numToAdd[i - 1] = Math.max(0, minHeight - ret.getQueueSize(i));
      sum += numToAdd[i - 1];
   }
   IntStream is = RAND.ints(sum, 0, possibleBlocks.size());
   is.forEachOrdered(new IntConsumer() {
      int curCol = 1;
      
      @Override
      public void accept(int arg0) {
         while (curCol <= Board.NUM_COLS && numToAdd[curCol - 1] <= 0) {
            curCol++;
         }
         if (curCol <= Board.NUM_COLS) {
            ret.addToQueue(curCol, possibleBlocks.get(arg0));
            numToAdd[curCol - 1]--;
         }
      }
   });
   return ret;
}
 
Example #29
Source File: SplittableRandom.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void forEachRemaining(IntConsumer consumer) {
    if (consumer == null) throw new NullPointerException();
    long i = index, f = fence;
    if (i < f) {
        index = f;
        SplittableRandom r = rng;
        int o = origin, b = bound;
        do {
            consumer.accept(r.internalNextInt(o, b));
        } while (++i < f);
    }
}
 
Example #30
Source File: TeeOpTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "IntStreamTestData", dataProviderClass = IntStreamTestDataProvider.class)
public void testIntOps(String name, final TestData.OfInt data) {
    class RecordingConsumer extends AbstractRecordingConsumer<Integer> implements IntConsumer {
        public void accept(int t) {
            list.add(t);
        }
    }
    final RecordingConsumer b = new RecordingConsumer();

    withData(data)
            .stream(s -> s.peek(b))
            .before(b::before)
            .after(b::after)
            .exercise();
}