下面列出了怎么用java.util.PrimitiveIterator.OfInt的API类实例代码及写法,或者点击链接到github查看源代码。
public static OfInt from(BitSet bitSet) {
return new OfInt() {
int curr = bitSet.nextSetBit(0);
@Override
public int nextInt() {
int result = curr;
this.curr = bitSet.nextSetBit(curr + 1);
return result;
}
@Override
public boolean hasNext() {
return curr >= 0;
}
};
}
/**
* @param it an iterator
* @param f a function which transforms values into iterators
* @return an iterator which yields the concatenation of the iterators
*/
public static <U> OfInt flatMap(Iterator<U> it, Function<U, OfInt> f) {
return new OfInt() {
OfInt curr = EMPTY;
private void prime() {
while (!curr.hasNext() && it.hasNext()) {
curr = f.apply(it.next());
}
}
@Override
public boolean hasNext() {
prime();
return curr.hasNext();
}
@Override
public int nextInt() {
prime();
return curr.nextInt();
}
};
}
/**
* @param min an inclusive start of the range
* @param max an exclusive end of the range
* @param f a function which transforms a number in the range into a value
* @return an iterator which yields the values returned by {@code f}
*/
public static OfInt range(long min, long max, LongToIntFunction f) {
return new OfInt() {
long i = min;
@Override
public boolean hasNext() {
return i < max;
}
@Override
public int nextInt() {
if (hasNext()) {
return f.applyAsInt(i++);
} else {
throw new NoSuchElementException();
}
}
};
}
public static OfInt codePointIterator(byte[] chunk) {
return new OfInt() {
private int idx = 2;
@Override
public int nextInt() {
int codePoint = decode(chunk, idx);
idx += prefixLength(chunk[idx]);
return codePoint;
}
@Override
public boolean hasNext() {
return idx < chunk.length;
}
};
}
public static OfInt reverseCodePointIterator(byte[] chunk) {
return new OfInt() {
int idx = chunk.length;
@Override
public int nextInt() {
while ((chunk[idx] & 0b11000000) == 0b10000000) {
idx--;
}
int codePoint = decode(chunk, idx);
idx--;
return codePoint;
}
@Override
public boolean hasNext() {
return idx > 2;
}
};
}
private <A> A collectSized(Supplier<A> supplier, ObjIntConsumer<A> accumulator, BiConsumer<A, A> combiner,
IntFunction<A> sizedSupplier, ObjIntConsumer<A> sizedAccumulator) {
if (isParallel())
return collect(supplier, accumulator, combiner);
java.util.Spliterator.OfInt spliterator = spliterator();
int size = intSize(spliterator);
A intermediate;
if (size != -1) {
intermediate = sizedSupplier.apply(size);
spliterator.forEachRemaining((IntConsumer) i -> sizedAccumulator.accept(intermediate, i));
} else {
intermediate = supplier.get();
spliterator.forEachRemaining((IntConsumer) i -> accumulator.accept(intermediate, i));
}
return intermediate;
}
@Test
public void compatibility() {
final TestData data = TestData.of("/io/jenetics/util/IndexStream.Random");
for (String[] line : data) {
final Random random = new Random(0);
final double p = Double.parseDouble(line[0]);
final OfInt it = indexes(random, 500, p).iterator();
for (int i = 1; i < line.length; ++i) {
final int index = Integer.parseInt(line[i]);
Assert.assertEquals(it.nextInt(), index);
}
Assert.assertFalse(it.hasNext());
}
}
@Test
public void reference() {
final int size = 5000;
final double p = 0.5;
final Random random1 = new Random(0);
final Random random2 = new Random(0);
for (int j = 0; j < 1; ++j) {
final OfInt it = indexes(random1, size, p).iterator();
final IndexStream stream2 = ReferenceRandomStream(
size, p, random2
);
while (it.hasNext()) {
Assert.assertEquals(it.nextInt(), stream2.next());
}
Assert.assertFalse(it.hasNext());
Assert.assertEquals(stream2.next(), -1);
}
}
/**
* underline -> camel e.g. __a_bc_d__e_ -> _ABcD_E_
*
* @param str
* @return
*/
public static String underline2upper(String str) {
StringBuilder sb = new StringBuilder();
boolean mode = false;
IntStream intStream = str.chars();
OfInt iterator = intStream.iterator();
while (iterator.hasNext()) {
int c = iterator.nextInt();
char cc = (char) c;
if (mode) {
if (cc >= 'a' && cc <= 'z') {
sb.append(((char) (cc - 32)));
mode = false;
continue;
}
if (cc == '_') {
sb.append('_');
continue;
}
sb.append((char) cc);
mode = false;
} else {
if (cc == '_') {
mode = true;
} else {
sb.append((char) cc);
}
}
}
if (mode) {
sb.append('_');
}
return sb.toString();
}
private Iterable<int[]> getRecords(IntCollection leftMatches) {
int size = leftMatches.size();
Collection<int[]> left = new ArrayList<>(size);
OfInt it = leftMatches.iterator();
while (it.hasNext()) {
int leftId = it.nextInt();
int[] record = leftRecords.get(leftId);
left.add(record);
}
return left;
}
private Int2ObjectMultimap<int[]> groupByValue(IntIterable matching) {
Int2ObjectMultimap<int[]> map = new Int2ObjectHashMultimap<>();
OfInt it = matching.iterator();
while (it.hasNext()) {
int id = it.nextInt();
int[] right = getRightRecord(id);
int rightValue = getRightValue(right);
map.put(rightValue, right);
}
return map;
}
@Override
public double calculateMinSimilarity(IntIterable matching) {
OfInt it = matching.iterator();
//does order have an impact on runtime?
while (it.hasNext() && shouldUpdate(minSimilarity)) {
int id = it.nextInt();
updateMinSimilarity(id);
}
return minSimilarity;
}
Iterable<int[]> getRecords(IntCollection ids) {
int size = ids.size();
Collection<int[]> result = new ArrayList<>(size);
OfInt it = ids.iterator();
while (it.hasNext()) {
int id = it.nextInt();
int[] record = records.get(id);
result.add(record);
}
return result;
}
public static boolean equals(OfInt a, OfInt b) {
while (a.hasNext()) {
if (a.nextInt() != b.nextInt()) {
return false;
}
}
return true;
}
/**
* @param it an iterator
* @param f a predicate
* @return an iterator which only yields values that satisfy the predicate
*/
public static OfInt filter(OfInt it, IntPredicate f) {
return new OfInt() {
private int next = 0;
private boolean primed = false;
private boolean done = false;
private void prime() {
if (!primed && !done) {
while (it.hasNext()) {
next = it.nextInt();
if (f.test(next)) {
primed = true;
return;
}
}
done = true;
}
}
@Override
public boolean hasNext() {
prime();
return !done;
}
@Override
public int nextInt() {
prime();
if (!primed) {
throw new NoSuchElementException();
}
primed = false;
return next;
}
};
}
/**
* @param it an iterator
* @param f a function which transforms values
* @return an iterator which yields the transformed values
*/
public static OfInt map(OfInt it, IntUnaryOperator f) {
return new OfInt() {
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public int nextInt() {
return f.applyAsInt(it.nextInt());
}
};
}
public static OfInt codeUnitIterator(byte[] chunk) {
return new OfInt() {
OfInt it = codePointIterator(chunk);
short low = -1;
@Override
public int nextInt() {
if (low == -1) {
int codePoint = it.nextInt();
if (codePoint < 0x10000) {
return codePoint;
} else {
low = (short) Character.lowSurrogate(codePoint);
return Character.highSurrogate(codePoint);
}
} else {
int val = low;
low = -1;
return val;
}
}
@Override
public boolean hasNext() {
return low != -1 || it.hasNext();
}
};
}
public static OfInt reverseCodeUnitIterator(byte[] chunk) {
return new OfInt() {
OfInt it = codePointIterator(chunk);
short high = -1;
@Override
public int nextInt() {
if (high == -1) {
int codePoint = it.nextInt();
if (codePoint < 0x10000) {
return codePoint;
} else {
high = (short) Character.highSurrogate(codePoint);
return Character.lowSurrogate(codePoint);
}
} else {
int val = high;
high = -1;
return val;
}
}
@Override
public boolean hasNext() {
return high != -1 || it.hasNext();
}
};
}
@Test
public void testDropWhile() {
assertArrayEquals(new int[] { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, IntStreamEx.range(100).dropWhile(
i -> i % 10 < 5).limit(10).toArray());
assertEquals(100, IntStreamEx.range(100).dropWhile(i -> i % 10 < 0).count());
assertEquals(0, IntStreamEx.range(100).dropWhile(i -> i % 10 < 10).count());
assertEquals(OptionalInt.of(0), IntStreamEx.range(100).dropWhile(i -> i % 10 < 0).findFirst());
assertEquals(OptionalInt.empty(), IntStreamEx.range(100).dropWhile(i -> i % 10 < 10).findFirst());
java.util.Spliterator.OfInt spltr = IntStreamEx.range(100).dropWhile(i -> i % 10 < 1).spliterator();
assertTrue(spltr.tryAdvance((int x) -> assertEquals(1, x)));
Builder builder = IntStream.builder();
spltr.forEachRemaining(builder);
assertArrayEquals(IntStreamEx.range(2, 100).toArray(), builder.build().toArray());
}
public OfInt iterator() {
return new OfInt() {
int pos = 0;
@Override
public boolean hasNext() {
return pos < size();
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return get(pos++);
}
@Override
public int nextInt() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return get(pos++);
}
};
}
@Override
public void copyValuesFrom(CommonArrayFS<Integer> v) {
clear();
Spliterator.OfInt si;
if (v instanceof IntegerArrayList) {
si = ((IntegerArrayList) v).spliterator();
} else if (v instanceof IntegerArray) {
si = ((IntegerArray) v).spliterator();
} else {
throw new ClassCastException("argument must be of class IntegerArray or IntegerArrayList");
}
si.forEachRemaining((int i) -> add(i));
}
/**
* @return -
* @see java.util.ArrayList#iterator()
*/
@Override
public OfInt iterator() {
return (null == intArrayAsList)
? intArrayList.iterator()
: intArrayAsList.iterator();
}
/**
* Version of forEach that doesn't box
* @param action -
*/
public void forEach(IntConsumer action) {
OfInt ii = iterator();
while (ii.hasNext()) {
action.accept(ii.nextInt());
}
}
@Override
public OfInt iterator() {
return new OfInt() {
int i = 0;
/* (non-Javadoc)
* @see java.util.PrimitiveIterator.OfInt#forEachRemaining(java.util.function.IntConsumer)
*/
@Override
public void forEachRemaining(IntConsumer action) {
final int sz = size();
for (; i < sz; i++) {
action.accept(theArray[i]);
}
}
@Override
public boolean hasNext() {
return i < size();
}
@Override
public Integer next() {
if (!hasNext())
throw new NoSuchElementException();
return get(i++);
}
@Override
public int nextInt() {
if (!hasNext())
throw new NoSuchElementException();
return get(i++);
}
};
}
public static IntStream toStream(OfInt it, long estimatedSize) {
return StreamSupport.intStream(Spliterators.spliterator(it, estimatedSize, Spliterator.ORDERED), false);
}
IntStreamEx(Spliterator.OfInt spliterator, StreamContext context) {
super(spliterator, context);
}
final IntStreamEx delegate(Spliterator.OfInt spliterator) {
return new IntStreamEx(spliterator, context);
}
/**
* Returns an {@code InputStream} lazily populated from the current
* {@code IntStreamEx}.
*
* <p>
* Note that only the least-significant byte of every number encountered in
* this stream is preserved in the resulting {@code InputStream}, other
* bytes are silently lost. Thus it's a caller responsibility to check
* whether this may cause problems.
*
* <p>
* This is a terminal operation.
*
* <p>
* When the resulting {@code InputStream} is closed, this
* {@code IntStreamEx} is closed as well.
*
* @return a new {@code InputStream}.
* @see #of(InputStream)
* @since 0.6.1
*/
public InputStream asByteInputStream() {
Spliterator.OfInt spltr = spliterator();
return new InputStream() {
private int last;
@Override
public int read() {
return spltr.tryAdvance((int val) -> last = val) ? (last & 0xFF) : -1;
}
@Override
public void close() {
IntStreamEx.this.close();
}
};
}
@Override
public OfInt iterator() {
return Spliterators.iterator(spliterator());
}
@Test
public void testBasics() {
assertFalse(IntStreamEx.of(1).isParallel());
assertTrue(IntStreamEx.of(1).parallel().isParallel());
assertFalse(IntStreamEx.of(1).parallel().sequential().isParallel());
AtomicInteger i = new AtomicInteger();
try (IntStreamEx s = IntStreamEx.of(1).onClose(i::incrementAndGet)) {
assertEquals(1, s.count());
}
assertEquals(1, i.get());
assertEquals(6, IntStreamEx.range(0, 4).sum());
assertEquals(3, IntStreamEx.range(0, 4).max().getAsInt());
assertEquals(0, IntStreamEx.range(0, 4).min().getAsInt());
assertEquals(1.5, IntStreamEx.range(0, 4).average().getAsDouble(), 0.000001);
assertEquals(4, IntStreamEx.range(0, 4).summaryStatistics().getCount());
assertArrayEquals(new int[] { 1, 2, 3 }, IntStreamEx.range(0, 5).skip(1).limit(3).toArray());
assertArrayEquals(new int[] { 1, 2, 3 }, IntStreamEx.of(3, 1, 2).sorted().toArray());
assertArrayEquals(new int[] { 1, 2, 3 }, IntStreamEx.of(1, 2, 1, 3, 2).distinct().toArray());
assertArrayEquals(new int[] { 2, 4, 6 }, IntStreamEx.range(1, 4).map(x -> x * 2).toArray());
assertArrayEquals(new long[] { 2, 4, 6 }, IntStreamEx.range(1, 4).mapToLong(x -> x * 2).toArray());
assertArrayEquals(new double[] { 2, 4, 6 }, IntStreamEx.range(1, 4).mapToDouble(x -> x * 2).toArray(), 0.0);
assertArrayEquals(new int[] { 1, 3 }, IntStreamEx.range(0, 5).filter(x -> x % 2 == 1).toArray());
assertEquals(6, IntStreamEx.of(1, 2, 3).reduce(Integer::sum).getAsInt());
assertEquals(Integer.MAX_VALUE, IntStreamEx.rangeClosed(1, Integer.MAX_VALUE).spliterator()
.getExactSizeIfKnown());
assertTrue(IntStreamEx.of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.ORDERED));
assertFalse(IntStreamEx.of(1, 2, 3).unordered().spliterator().hasCharacteristics(Spliterator.ORDERED));
OfInt iterator = IntStreamEx.of(1, 2, 3).iterator();
assertEquals(1, iterator.nextInt());
assertEquals(2, iterator.nextInt());
assertEquals(3, iterator.nextInt());
assertFalse(iterator.hasNext());
List<Integer> list = new ArrayList<>();
IntStreamEx.range(10).parallel().forEachOrdered(list::add);
assertEquals(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), list);
assertTrue(IntStreamEx.empty().noneMatch(x -> true));
assertFalse(IntStreamEx.of(1).noneMatch(x -> true));
assertTrue(IntStreamEx.of(1).noneMatch(x -> false));
}