Java Code Examples for java.util.function.IntUnaryOperator

The following examples show how to use java.util.function.IntUnaryOperator. These examples are extracted from open source projects. 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 Project: j2objc   Source File: IntPipeline.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public final IntStream map(IntUnaryOperator mapper) {
    Objects.requireNonNull(mapper);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        public Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    downstream.accept(mapper.applyAsInt(t));
                }
            };
        }
    };
}
 
Example 2
Source Project: dragonwell8_jdk   Source File: IntStream.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an infinite sequential ordered {@code IntStream} produced by iterative
 * application of a function {@code f} to an initial element {@code seed},
 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 * {@code f(f(seed))}, etc.
 *
 * <p>The first element (position {@code 0}) in the {@code IntStream} will be
 * the provided {@code seed}.  For {@code n > 0}, the element at position
 * {@code n}, will be the result of applying the function {@code f} to the
 * element at position {@code n - 1}.
 *
 * @param seed the initial element
 * @param f a function to be applied to the previous element to produce
 *          a new element
 * @return A new sequential {@code IntStream}
 */
public static IntStream iterate(final int seed, final IntUnaryOperator f) {
    Objects.requireNonNull(f);
    final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() {
        int t = seed;

        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public int nextInt() {
            int v = t;
            t = f.applyAsInt(t);
            return v;
        }
    };
    return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
            iterator,
            Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
}
 
Example 3
Source Project: jdk8u-dev-jdk   Source File: IntPipeline.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public final IntStream map(IntUnaryOperator mapper) {
    Objects.requireNonNull(mapper);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    downstream.accept(mapper.applyAsInt(t));
                }
            };
        }
    };
}
 
Example 4
Source Project: TencentKona-8   Source File: IntPipeline.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public final IntStream map(IntUnaryOperator mapper) {
    Objects.requireNonNull(mapper);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    downstream.accept(mapper.applyAsInt(t));
                }
            };
        }
    };
}
 
Example 5
Source Project: consulo   Source File: IntEnumerator.java    License: Apache License 2.0 6 votes vote down vote up
void dump(DataOutputStream stream, IntUnaryOperator idRemapping) throws IOException {
  DataInputOutputUtil.writeINT(stream, myIds.size());
  IOException[] exception = new IOException[1];
  myIds.forEach(id -> {
    try {
      int remapped = idRemapping.applyAsInt(id);
      if (remapped == 0) {
        exception[0] = new IOException("remapping is not found for " + id);
        return false;
      }
      DataInputOutputUtil.writeINT(stream, remapped);
    }
    catch (IOException e) {
      exception[0] = e;
      return false;
    }
    return true;
  });
  if (exception[0] != null) {
    throw exception[0];
  }
}
 
Example 6
/**
 * Returns an infinite sequential ordered {@code IntStream} produced by iterative
 * application of a function {@code f} to an initial element {@code seed},
 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 * {@code f(f(seed))}, etc.
 *
 * <p>The first element (position {@code 0}) in the {@code IntStream} will be
 * the provided {@code seed}.  For {@code n > 0}, the element at position
 * {@code n}, will be the result of applying the function {@code f} to the
 * element at position {@code n - 1}.
 *
 * @param seed the initial element
 * @param f a function to be applied to to the previous element to produce
 *          a new element
 * @return A new sequential {@code IntStream}
 */
public static IntStream iterate(final int seed, final IntUnaryOperator f) {
    Objects.requireNonNull(f);
    final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() {
        int t = seed;

        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public int nextInt() {
            int v = t;
            t = f.applyAsInt(t);
            return v;
        }
    };
    return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
            iterator,
            Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
}
 
Example 7
Source Project: jdk8u_jdk   Source File: IntStream.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an infinite sequential ordered {@code IntStream} produced by iterative
 * application of a function {@code f} to an initial element {@code seed},
 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 * {@code f(f(seed))}, etc.
 *
 * <p>The first element (position {@code 0}) in the {@code IntStream} will be
 * the provided {@code seed}.  For {@code n > 0}, the element at position
 * {@code n}, will be the result of applying the function {@code f} to the
 * element at position {@code n - 1}.
 *
 * @param seed the initial element
 * @param f a function to be applied to the previous element to produce
 *          a new element
 * @return A new sequential {@code IntStream}
 */
public static IntStream iterate(final int seed, final IntUnaryOperator f) {
    Objects.requireNonNull(f);
    final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() {
        int t = seed;

        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public int nextInt() {
            int v = t;
            t = f.applyAsInt(t);
            return v;
        }
    };
    return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
            iterator,
            Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
}
 
Example 8
Source Project: Java8CN   Source File: IntPipeline.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public final IntStream map(IntUnaryOperator mapper) {
    Objects.requireNonNull(mapper);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    downstream.accept(mapper.applyAsInt(t));
                }
            };
        }
    };
}
 
Example 9
Source Project: jdk8u-jdk   Source File: IntPipeline.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public final IntStream map(IntUnaryOperator mapper) {
    Objects.requireNonNull(mapper);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    downstream.accept(mapper.applyAsInt(t));
                }
            };
        }
    };
}
 
Example 10
Source Project: FreeBuilder   Source File: NullableMapperMethodTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void mapCanAcceptPrimitiveFunctionalInterface() {
  behaviorTester
      .with(new Processor(features))
      .with(SourceBuilder.forTesting()
          .addLine("package com.example;")
          .addLine("@%s", FreeBuilder.class)
          .addLine("public interface DataType {")
          .addLine("  @%s Integer %s;", Nullable.class, convention.get("property"))
          .addLine("")
          .addLine("  public static class Builder extends DataType_Builder {")
          .addLine("    @Override public Builder mapProperty(%s mapper) {",
              IntUnaryOperator.class)
          .addLine("      return super.mapProperty(mapper);")
          .addLine("    }")
          .addLine("  }")
          .addLine("}"))
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .%s(11)", convention.set("property"))
          .addLine("    .mapProperty(a -> a + 3)")
          .addLine("    .build();")
          .addLine("assertEquals(14, (int) value.%s);", convention.get("property"))
          .build())
      .runTest();
}
 
Example 11
Source Project: JDKSourceCode1.8   Source File: IntPipeline.java    License: MIT License 6 votes vote down vote up
@Override
public final IntStream map(IntUnaryOperator mapper) {
    Objects.requireNonNull(mapper);
    return new StatelessOp<Integer>(this, StreamShape.INT_VALUE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<Integer> opWrapSink(int flags, Sink<Integer> sink) {
            return new Sink.ChainedInt<Integer>(sink) {
                @Override
                public void accept(int t) {
                    downstream.accept(mapper.applyAsInt(t));
                }
            };
        }
    };
}
 
Example 12
Source Project: jdk8u-jdk   Source File: SetAllTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "int")
public void testSetAllInt(String name, int size, IntUnaryOperator generator, int[] expected) {
    int[] result = new int[size];
    Arrays.setAll(result, generator);
    assertEquals(result, expected, "setAll(int[], IntUnaryOperator) case " + name + " failed.");

    // ensure fresh array
    result = new int[size];
    Arrays.parallelSetAll(result, generator);
    assertEquals(result, expected, "parallelSetAll(int[], IntUnaryOperator) case " + name + " failed.");
}
 
Example 13
Source Project: openjdk-8-source   Source File: SetAllTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "int")
public void testSetAllInt(String name, int size, IntUnaryOperator generator, int[] expected) {
    int[] result = new int[size];
    Arrays.setAll(result, generator);
    assertEquals(result, expected, "setAll(int[], IntUnaryOperator) case " + name + " failed.");

    // ensure fresh array
    result = new int[size];
    Arrays.parallelSetAll(result, generator);
    assertEquals(result, expected, "parallelSetAll(int[], IntUnaryOperator) case " + name + " failed.");
}
 
Example 14
Source Project: crate   Source File: ArrayLengthQuery.java    License: Apache License 2.0 5 votes vote down vote up
NumTermsPerDocTwoPhaseIterator(LeafReader reader,
                               IntUnaryOperator numTermsOfDoc,
                               IntPredicate matches) {
    super(DocIdSetIterator.all(reader.maxDoc()));
    this.numTermsOfDoc = numTermsOfDoc;
    this.matches = matches;
}
 
Example 15
Source Project: IPAddress   Source File: AddressDivisionGrouping.java    License: Apache License 2.0 5 votes vote down vote up
protected static long getLongCount(IntUnaryOperator countProvider, int segCount) {
	if(segCount == 0) {
		return 1;
	}
	long result = countProvider.applyAsInt(0);
	for(int i = 1; i < segCount; i++) {
		result *= countProvider.applyAsInt(i);
	}
	return result;
}
 
Example 16
Source Project: servicetalk   Source File: DefaultSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> Publisher<Buffer> serialize(final Publisher<T> source, final BufferAllocator allocator,
                                       final Class<T> type, final IntUnaryOperator bytesEstimator) {
    return new SubscribablePublisher<Buffer>() {
        @Override
        protected void handleSubscribe(final Subscriber<? super Buffer> subscriber) {
            applySerializer0(subscriber, allocator, bytesEstimator, serializationProvider.getSerializer(type),
                    source);
        }
    };
}
 
Example 17
Source Project: openjdk-jdk9   Source File: ReaderTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void checkAndSetOrder(IntPredicate expectedValue,
                              IntUnaryOperator newValue) {
    if (!expectedValue.test(invocationOrder)) {
        throw new TestSupport.AssertionFailedException(
                expectedValue + " -> " + newValue);
    }
    invocationOrder = newValue.applyAsInt(invocationOrder);
}
 
Example 18
Source Project: ph-commons   Source File: IntIntMap.java    License: Apache License 2.0 5 votes vote down vote up
public int computeIfAbsent (final int key, @Nonnull final IntUnaryOperator aProvider)
{
  int ret = get (key);
  if (ret == NO_VALUE)
  {
    ret = aProvider.applyAsInt (key);
    if (ret != NO_VALUE)
      put (key, ret);
  }
  return ret;
}
 
Example 19
public static IntUnaryOperator createReplaceEntityIdFunc(IntSupplier id1Supplier, IntSupplier id2Supplier) {
	return (entityId) -> {
		int entityId1 = id1Supplier.getAsInt();
		int entityId2 = id2Supplier.getAsInt();
		if (entityId == entityId1) {
			return entityId2;
		}
		if (entityId == entityId2) {
			return entityId1;
		}
		return entityId;
	};
}
 
Example 20
Source Project: j2objc   Source File: IntUnaryOperatorTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testAndThen_null() throws Exception {
  IntUnaryOperator plusOne = x -> x + 1;
  try {
    plusOne.andThen(null);
    fail();
  } catch (NullPointerException expected) {}
}
 
Example 21
Source Project: agrona   Source File: Int2IntCounterMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldComputeIfAbsent()
{
    final int testKey = 7;
    final int testValue = 7;

    final IntUnaryOperator function = (i) -> testValue;

    assertEquals(map.initialValue(), map.get(testKey));

    assertThat(map.computeIfAbsent(testKey, function), is(testValue));
    assertThat(map.get(testKey), is(testValue));
}
 
Example 22
Source Project: Cardshifter   Source File: ECSResourceData.java    License: Apache License 2.0 4 votes vote down vote up
public void changeBy(int value, IntUnaryOperator fix) {
    int newValue = current + value;
    set(fix.applyAsInt(newValue));
}
 
Example 23
@Override
public <T> HttpSerializer<T> serializerFor(final Class<T> type, final IntUnaryOperator bytesEstimator) {
    return new DefaultSizeAwareClassHttpSerializer<>(type, serializer, addContentType, bytesEstimator);
}
 
Example 24
Source Project: rheem   Source File: JavaReservoirSampleOperator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance.
 */
public JavaReservoirSampleOperator(IntUnaryOperator sampleSizeFunction, DataSetType<Type> type, LongUnaryOperator seed) {
    super(sampleSizeFunction, type, Methods.RESERVOIR, seed);
}
 
Example 25
Source Project: servicetalk   Source File: DefaultSerializer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T> BlockingIterable<Buffer> serialize(final BlockingIterable<T> source, final BufferAllocator allocator,
                                              final Class<T> type, final IntUnaryOperator bytesEstimator) {
    return applySerializer0(allocator, bytesEstimator, source, serializationProvider.getSerializer(type));
}
 
Example 26
Source Project: servicetalk   Source File: DefaultSerializer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T> Iterable<Buffer> serialize(final Iterable<T> source, final BufferAllocator allocator,
                                      final TypeHolder<T> typeHolder, final IntUnaryOperator bytesEstimator) {
    final StreamingSerializer serializer = serializationProvider.getSerializer(typeHolder);
    return applySerializer0(allocator, bytesEstimator, source, serializer);
}
 
Example 27
Source Project: IPAddress   Source File: IPAddressSection.java    License: Apache License 2.0 4 votes vote down vote up
protected static <R extends IPAddressSection, S extends IPAddressSegment> R setPrefixLength(
		R original,
		IPAddressCreator<?, R, ?, S, ?> creator,
		int networkPrefixLength,
		boolean withZeros,
		boolean noShrink,
		boolean singleOnly,
		SegFunction<R, S> segProducer) throws IncompatibleAddressException {
	Integer existingPrefixLength = original.getNetworkPrefixLength();
	if(existingPrefixLength != null) {
		if(networkPrefixLength == existingPrefixLength.intValue()) {
			return original;
		} else if(noShrink && networkPrefixLength > existingPrefixLength.intValue()) {
			checkSubnet(original, networkPrefixLength);
			return original;
		}
	}
	checkSubnet(original, networkPrefixLength);
	IPAddressNetwork<?, R, ?, S, ?> network = creator.getNetwork();
	int maskBits;
	IntUnaryOperator segmentMaskProducer = null;
	if(network.getPrefixConfiguration().allPrefixedAddressesAreSubnets()) {
		if(existingPrefixLength != null) {
			if(networkPrefixLength > existingPrefixLength.intValue()) {
				if(withZeros) {
					maskBits = existingPrefixLength;
				} else {
					maskBits = networkPrefixLength;
				}
			} else { // networkPrefixLength < existingPrefixLength.intValue()
				maskBits = networkPrefixLength;
			} 
		} else {
			maskBits = networkPrefixLength;
		}
	} else {
		if(existingPrefixLength != null) {
			if(withZeros) {
				R leftMask, rightMask;
				if(networkPrefixLength > existingPrefixLength.intValue()) {
					leftMask = network.getNetworkMaskSection(existingPrefixLength);
					rightMask = network.getHostMaskSection(networkPrefixLength);
				} else {
					leftMask = network.getNetworkMaskSection(networkPrefixLength);
					rightMask = network.getHostMaskSection(existingPrefixLength);
				}
				segmentMaskProducer = i -> {
					int val1 = segProducer.apply(leftMask, i).getSegmentValue();
					int val2 = segProducer.apply(rightMask, i).getSegmentValue();
					return val1 | val2;
				};
			}
		}
		maskBits = original.getBitCount();
	}
	if(segmentMaskProducer == null) {
		R mask = network.getNetworkMaskSection(maskBits);
		segmentMaskProducer = i -> segProducer.apply(mask, i).getSegmentValue();
	}
	return getSubnetSegments(
			original,
			cacheBits(networkPrefixLength),
			creator,
			true,
			i -> segProducer.apply(original, i),
			segmentMaskProducer,
			singleOnly);
}
 
Example 28
Source Project: rheem   Source File: SparkRandomPartitionSampleOperator.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance.
 */
public SparkRandomPartitionSampleOperator(IntUnaryOperator sampleSizeFunction, DataSetType<Type> type, LongUnaryOperator seedFunction) {
    super(sampleSizeFunction, type, Methods.RANDOM, seedFunction);
}
 
Example 29
Source Project: es6draft   Source File: TypedArrayFunctions.java    License: MIT License 4 votes vote down vote up
private static final void put(IntUnaryOperator src, int srcPos, ByteBuffer dest, int destPos, int length) {
    for (int n = destPos, k = srcPos; k < srcPos + length;) {
        dest.put(n++, (byte) src.applyAsInt(k++));
    }
}
 
Example 30
Source Project: parquet-mr   Source File: IndexIterator.java    License: Apache License 2.0 4 votes vote down vote up
static PrimitiveIterator.OfInt filterTranslate(int arrayLength, IntPredicate filter, IntUnaryOperator translator) {
  return new IndexIterator(0, arrayLength, filter, translator);
}