下面列出了怎么用java.util.function.IntConsumer的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
}
@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);
}
/**
* 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;
}
@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);
}
}
@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);
}
};
}
};
}
@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);
}
};
}
};
}
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);
}
@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);
}
}
@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;
}
@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;
}
@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--]);
}
}
}
@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);
}
};
}
};
}
@Override
public boolean tryAdvance(IntConsumer action) {
Objects.requireNonNull(action);
if (count == -2) {
action.accept(first);
count = -1;
return true;
}
else {
return false;
}
}
private void testAlreadyAborted(final IntConsumer action)
{
final int index = 128;
final int recordIndex = index - HEADER_LENGTH;
when(buffer.getInt(lengthOffset(recordIndex))).thenReturn(10);
when(buffer.getInt(typeOffset(recordIndex))).thenReturn(PADDING_MSG_TYPE_ID);
final IllegalStateException exception = assertThrows(IllegalStateException.class,
() -> action.accept(index));
assertEquals("claimed space previously aborted", exception.getMessage());
}
@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);
}
}
@Override
default void forEachRemaining(Consumer<? super Integer> consumer) {
if (consumer instanceof IntConsumer) {
forEachRemaining((IntConsumer) consumer);
} else {
checkCriticalNotNull(consumer);
forEachRemaining((IntConsumer) consumer::accept);
}
}
/**
* {@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);
}
}
@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);
}
}
/**
* 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();
}
public boolean tryAdvance(IntConsumer consumer) {
if (consumer == null) throw new NullPointerException();
long i = index, f = fence;
if (i < f) {
consumer.accept(ThreadLocalRandom.current().internalNextInt(origin, bound));
index = i + 1;
return true;
}
return false;
}
@Override
public void forEachRemaining(IntConsumer consumer) {
if (buffer == null && !finished) {
Objects.requireNonNull(consumer);
init();
ph.wrapAndCopyInto((Sink.OfInt) consumer::accept, spliterator);
finished = true;
}
else {
do { } while (tryAdvance(consumer));
}
}
@Override
public boolean tryAdvance(IntConsumer action) {
Objects.requireNonNull(action);
action.accept(s.getAsInt());
return true;
}
@Override
public void forEachRemaining(IntConsumer action) {
int[] a; int i, hi; // hoist accesses and checks from loop
if (action == null)
throw new NullPointerException();
if ((a = array).length >= (hi = fence) &&
(i = index) >= 0 && i < (index = hi)) {
do { action.accept(a[i]); } while (++i < hi);
}
}
/**
* {@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);
}
}
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);
}
}
/**
* 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;
}
@Override
public void forEach(IntConsumer action) {
if (!isParallel()) {
adapt(sourceStageSpliterator()).forEachRemaining(action);
}
else {
super.forEach(action);
}
}
@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);
}
}
/**
* 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();
}
@Override
public boolean tryAdvance(IntConsumer action) {
Objects.requireNonNull(action);
action.accept(s.getAsInt());
return true;
}