java.util.function.IntUnaryOperator Java Examples

The following examples show how to use java.util.function.IntUnaryOperator. 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: IntStream.java    From jdk8u_jdk with 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 #2
Source File: IntPipeline.java    From jdk8u-dev-jdk with 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 #3
Source File: IntPipeline.java    From j2objc with 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 #4
Source File: IntPipeline.java    From TencentKona-8 with 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 File: IntPipeline.java    From Java8CN with 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 #6
Source File: IntPipeline.java    From JDKSourceCode1.8 with 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 #7
Source File: IntPipeline.java    From jdk8u-jdk with 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 #8
Source File: IntStream.java    From openjdk-jdk8u-backup with 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 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 #9
Source File: IntEnumerator.java    From consulo with 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 #10
Source File: NullableMapperMethodTest.java    From FreeBuilder with 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 File: IntStream.java    From dragonwell8_jdk with 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 #12
Source File: Int2IntCounterMapTest.java    From agrona with 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 #13
Source File: DefaultSerializer.java    From servicetalk with 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 #14
Source File: ReaderTest.java    From openjdk-jdk9 with 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 #15
Source File: IntIntMap.java    From ph-commons with 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 #16
Source File: ArrayLengthQuery.java    From crate with 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 #17
Source File: SetAllTest.java    From openjdk-8-source with 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 #18
Source File: SetAllTest.java    From jdk8u-jdk with 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 #19
Source File: AddressDivisionGrouping.java    From IPAddress with 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 #20
Source File: EntityRewriteFactory.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #21
Source File: IntUnaryOperatorTest.java    From j2objc with 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 #22
Source File: JavaReservoirSampleOperator.java    From rheem with 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 #23
Source File: IndexIterator.java    From parquet-mr with Apache License 2.0 4 votes vote down vote up
private IndexIterator(int startIndex, int endIndex, IntPredicate filter, IntUnaryOperator translator) {
  this.endIndex = endIndex;
  this.filter = filter;
  this.translator = translator;
  index = nextPageIndex(startIndex);
}
 
Example #24
Source File: DefaultHttpSerializationProvider.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
@Override
public <T> HttpSerializer<T> serializerFor(final Class<T> type, final IntUnaryOperator bytesEstimator) {
    return new DefaultSizeAwareClassHttpSerializer<>(type, serializer, addContentType, bytesEstimator);
}
 
Example #25
Source File: TypedArrayFunctions.java    From es6draft with 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 #26
Source File: EntityRewriteCommand.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void rewrite(ByteBuf from, ByteBuf to, IntUnaryOperator rewritefunc) {
	writeEntityId(to, rewritefunc.applyAsInt(readEntityId(from)));
}
 
Example #27
Source File: AbstractSuggestionBoxValueCellEditor.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
private void makeComboBoxDropDownWider() {
	Object child = comboBox.getAccessibleContext().getAccessibleChild(0);
	BasicComboPopup popup = (BasicComboPopup) child;
	Insets borderInsets = popup.getBorder().getBorderInsets(popup);
	JList<?> list = popup.getList();
	Dimension preferred = list.getPreferredSize();

	IntUnaryOperator extractWidth = i -> comboBox.getRenderer()
			.getListCellRendererComponent(list, model.getElementAt(i), i, false, false)
			.getPreferredSize().width + 3;
	preferred.width = IntStream.range(0, model.getSize()).map(extractWidth)
			.reduce(comboBox.getWidth() - borderInsets.left - borderInsets.right, Integer::max);

	int itemCount = comboBox.getItemCount();
	int rowHeight = 10;
	if (itemCount > 0) {
		rowHeight = preferred.height / itemCount;
	}
	int maxHeight = comboBox.getMaximumRowCount() * rowHeight;
	preferred.height = Math.min(preferred.height, maxHeight);

	Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
	JScrollPane scrollPane = (JScrollPane) c;

	scrollPane.setPreferredSize(preferred);
	scrollPane.setMaximumSize(preferred);

	if (popup.isShowing()) { // 
		// a little trick to fire Popup.showPopup method that takes care of correct display
		popup.setLocation(comboBox.getLocationOnScreen().x, popup.getLocationOnScreen().y - 1);
	}

	Dimension popupSize = new Dimension();
	popupSize.width = preferred.width + borderInsets.left + borderInsets.right;
	popupSize.height = preferred.height + borderInsets.top + borderInsets.bottom;
	Component parent = popup.getParent();
	if (parent != null) {
		parent.setSize(popupSize);
		parent.validate();
		parent.repaint();
	}
}
 
Example #28
Source File: IndexIterator.java    From parquet-mr with 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);
}
 
Example #29
Source File: IPAddressSection.java    From IPAddress with 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 #30
Source File: DefaultSerializer.java    From servicetalk with 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);
}