Java 类java.util.OptionalInt 实例源码

项目:java-velocypack-module-jdk8    文件:VPackOptionalTest.java   
@Test
public void serializeOptionalPrimitive() {
    final OptionalPrimitiveTestEntity entity = new OptionalPrimitiveTestEntity();
    entity.d = OptionalDouble.of(69.5);
    entity.i = OptionalInt.of(69);
    entity.l = OptionalLong.of(69L);

    final VPackSlice vpack = vp.serialize(entity);
    assertThat(vpack, is(notNullValue()));
    assertThat(vpack.isObject(), is(true));
    assertThat(vpack.get("d").isDouble(), is(true));
    assertThat(vpack.get("d").getAsDouble(), is(69.5));
    assertThat(vpack.get("i").isInteger(), is(true));
    assertThat(vpack.get("i").getAsInt(), is(69));
    assertThat(vpack.get("l").isInteger(), is(true));
    assertThat(vpack.get("l").getAsLong(), is(69L));
}
项目:amazon-kinesis-video-streams-parser-library    文件:StreamingMkvReader.java   
StreamingMkvReader(boolean requirePath,
        Collection<EBMLTypeInfo> typeInfosToRead,
        ParserByteSource byteSource,
        OptionalInt maxContentBytesAtOnce) {
    this.requirePath = requirePath;
    typeInfosToRead.stream().forEach(t -> Validate.isTrue(t.getType() != EBMLTypeInfo.TYPE.MASTER));
    this.typeInfosToRead = new HashSet(typeInfosToRead);

    this.byteSource = byteSource;
    this.mkvStreamReaderCallback = new MkvStreamReaderCallback(this.requirePath, elementFilter());
    this.previousDataElement = Optional.empty();
    MkvTypeInfoProvider typeInfoProvider = new MkvTypeInfoProvider();
    try {
        typeInfoProvider.load();
    } catch (IllegalAccessException e) {
        //TODO: fix this
        throw new RuntimeException("Could not load mkv info", e);
    }
    if (maxContentBytesAtOnce.isPresent()) {
        this.parser = new EBMLParser(typeInfoProvider, mkvStreamReaderCallback, maxContentBytesAtOnce.getAsInt());
    } else {
        this.parser = new EBMLParser(typeInfoProvider, mkvStreamReaderCallback);
    }
}
项目:openjdk-jdk10    文件:ReaderTest.java   
@Test
public void frameStart() {
    final long[] payloads = {0, 126, 65536, Integer.MAX_VALUE + 1L};
    final OptionalInt[] masks = {empty(), of(-1), of(0), of(0xCAFEBABE),
            of(Integer.MAX_VALUE), of(Integer.MIN_VALUE)};
    for (boolean fin : new boolean[]{true, false}) {
        for (boolean rsv1 : new boolean[]{true, false}) {
            for (boolean rsv2 : new boolean[]{true, false}) {
                for (boolean rsv3 : new boolean[]{true, false}) {
                    for (Opcode opcode : Opcode.values()) {
                        for (long payloadLen : payloads) {
                            for (OptionalInt mask : masks) {
                                verifyFrameStart(fin, rsv1, rsv2, rsv3, opcode, payloadLen, mask);
                            }
                        }
                    }
                }
            }
        }
    }
    System.out.println("Frames: " + frames + ", Total cases: " + cases);
}
项目:openjdk-jdk10    文件:HeaderWriterTest.java   
private void verify(boolean fin,
                    boolean rsv1,
                    boolean rsv2,
                    boolean rsv3,
                    Opcode opcode,
                    long payloadLen,
                    OptionalInt mask) {
    frames++;
    HeaderWriter writer = new HeaderWriter();
    ByteBuffer expected = ByteBuffer.allocate(Frame.MAX_HEADER_SIZE_BYTES);
    writer.fin(fin).rsv1(rsv1).rsv2(rsv2).rsv3(rsv3).opcode(opcode).payloadLen(payloadLen);
    mask.ifPresentOrElse(writer::mask, writer::noMask);
    writer.write(expected);
    expected.flip();
    verifyPermutations(expected, writer,
            () -> writer.fin(fin),
            () -> writer.rsv1(rsv1),
            () -> writer.rsv2(rsv2),
            () -> writer.rsv3(rsv3),
            () -> writer.opcode(opcode),
            () -> writer.payloadLen(payloadLen),
            () -> mask.ifPresentOrElse(writer::mask, writer::noMask));
}
项目:hekate    文件:RpcMethodInfo.java   
private static OptionalInt findAffinityArg(Method meth) {
    OptionalInt affinityArg = OptionalInt.empty();

    if (meth.getParameterCount() > 0) {
        for (int i = 0; i < meth.getParameterCount() && !affinityArg.isPresent(); i++) {
            Annotation[] annotations = meth.getParameterAnnotations()[i];

            for (int j = 0; j < annotations.length; j++) {
                if (RpcAffinityKey.class.isAssignableFrom(annotations[j].annotationType())) {
                    affinityArg = OptionalInt.of(i);

                    break;
                }
            }
        }
    }

    return affinityArg;
}
项目:L2J-Global    文件:CeremonyOfChaosEvent.java   
public List<CeremonyOfChaosMember> getWinners()
{
    final List<CeremonyOfChaosMember> winners = new ArrayList<>();
    //@formatter:off
    final OptionalInt winnerLifeTime = getMembers().values().stream()
        .mapToInt(CeremonyOfChaosMember::getLifeTime)
        .max();

    if(winnerLifeTime.isPresent())
    {
        getMembers().values().stream()
            .sorted(Comparator.comparingLong(CeremonyOfChaosMember::getLifeTime)
                .reversed()
                .thenComparingInt(CeremonyOfChaosMember::getScore)
                .reversed())
            .filter(member -> member.getLifeTime() == winnerLifeTime.getAsInt())
            .collect(Collectors.toCollection(() -> winners));
    }

    //@formatter:on
    return winners;
}
项目:athena    文件:IntentListCompilers.java   
@Override
protected void execute() {
    IntentExtensionService service = get(IntentExtensionService.class);
    OptionalInt length = service.getCompilers().keySet().stream()
            .mapToInt(s -> s.getName().length())
            .max();
    if (length.isPresent()) {
        service.getCompilers().entrySet().forEach(e -> {
            print("%-" + length.getAsInt() + "s\t%s",
                  e.getKey().getName(),
                  e.getValue().getClass().getName());
        });
    } else {
        print("There are no compilers registered.");
    }

}
项目:java-velocypack-module-jdk8    文件:VPackJdk8Module.java   
@Override
public <C extends VPackSetupContext<C>> void setup(final C context) {
    context.registerDeserializer(Instant.class, VPackJdk8Deserializers.INSTANT);
    context.registerDeserializer(LocalDate.class, VPackJdk8Deserializers.LOCAL_DATE);
    context.registerDeserializer(LocalDateTime.class, VPackJdk8Deserializers.LOCAL_DATE_TIME);
    context.registerDeserializer(ZonedDateTime.class, VPackJdk8Deserializers.ZONED_DATE_TIME);
    context.registerDeserializer(OffsetDateTime.class, VPackJdk8Deserializers.OFFSET_DATE_TIME);
    context.registerDeserializer(ZoneId.class, VPackJdk8Deserializers.ZONE_ID);
    context.registerDeserializer(Optional.class, VPackJdk8Deserializers.OPTIONAL, true);
    context.registerDeserializer(OptionalDouble.class, VPackJdk8Deserializers.OPTIONAL_DOUBLE, true);
    context.registerDeserializer(OptionalInt.class, VPackJdk8Deserializers.OPTIONAL_INT, true);
    context.registerDeserializer(OptionalLong.class, VPackJdk8Deserializers.OPTIONAL_LONG, true);

    context.registerSerializer(Instant.class, VPackJdk8Serializers.INSTANT);
    context.registerSerializer(LocalDate.class, VPackJdk8Serializers.LOCAL_DATE);
    context.registerSerializer(LocalDateTime.class, VPackJdk8Serializers.LOCAL_DATE_TIME);
    context.registerSerializer(ZonedDateTime.class, VPackJdk8Serializers.ZONED_DATE_TIME);
    context.registerSerializer(OffsetDateTime.class, VPackJdk8Serializers.OFFSET_DATE_TIME);
    context.registerSerializer(ZoneId.class, VPackJdk8Serializers.ZONE_ID);
    context.registerSerializer(Optional.class, VPackJdk8Serializers.OPTIONAL);
    context.registerSerializer(OptionalDouble.class, VPackJdk8Serializers.OPTIONAL_DOUBLE);
    context.registerSerializer(OptionalInt.class, VPackJdk8Serializers.OPTIONAL_INT);
    context.registerSerializer(OptionalLong.class, VPackJdk8Serializers.OPTIONAL_LONG);
}
项目:openjdk-jdk10    文件:BasicInt.java   
@Test(groups = "unit")
public void testEmpty() {
    OptionalInt empty = OptionalInt.empty();
    OptionalInt present = OptionalInt.of(1);

    // empty
    assertTrue(empty.equals(empty));
    assertTrue(empty.equals(OptionalInt.empty()));
    assertTrue(!empty.equals(present));
    assertTrue(0 == empty.hashCode());
    assertTrue(!empty.toString().isEmpty());
    assertTrue(!empty.isPresent());

    empty.ifPresent(v -> { fail(); });

    AtomicBoolean emptyCheck = new AtomicBoolean();
    empty.ifPresentOrElse(v -> fail(), () -> emptyCheck.set(true));
    assertTrue(emptyCheck.get());

    try {
        empty.ifPresentOrElse(v -> fail(), () -> { throw new ObscureException(); });
        fail();
    } catch (ObscureException expected) {
    } catch (AssertionError e) {
        throw e;
    } catch (Throwable t) {
        fail();
    }

    assertEquals(2, empty.orElse(2));
    assertEquals(2, empty.orElseGet(()-> 2));
}
项目:GitHub    文件:JdkOptionalBuilderFactory.java   
static void use() {
  new ApplBuilder()
      .a(1)
      .b("")
      .c(1)
      .build();

  new BbzBuilder(java.util.Optional.empty(), OptionalInt.empty()).build();
}
项目:beanmother    文件:JavaOptionalConverterModuleTest.java   
@Test
public void testNumberToOptionalIntConverter(){
    converter = new JavaOptionalConverterModule.NumberToOptionalIntConverter();

    assertTrue(converter.canHandle(1l, TypeToken.of(OptionalInt.class)));
    assertFalse(converter.canHandle(1l, TypeToken.of(OptionalLong.class)));

    Object result = converter.convert(1l, TypeToken.of(OptionalInt.class));
    assertTrue(result instanceof OptionalInt);
    assertEquals(1, ((OptionalInt) result).getAsInt());
}
项目:drift    文件:SimpleMessageEncoding.java   
@Override
public OptionalInt extractResponseSequenceId(ByteBuf buffer)
{
    try {
        TTransport inputTransport = new TChannelBufferInputTransport(buffer.duplicate());
        TMessage message = protocolFactory.getProtocol(inputTransport).readMessageBegin();
        return OptionalInt.of(message.getSequenceId());
    }
    catch (Throwable ignored) {
    }
    return OptionalInt.empty();
}
项目:L2J-Global    文件:ZoneManager.java   
@Override
public final void load()
{
    _classZones.clear();
    _spawnTerritories.clear();
    parseDatapackDirectory("data/zones", false);
    parseDatapackDirectory("data/zones/spawnZones", false);
    LOGGER.info(getClass().getSimpleName() + ": Loaded " + _classZones.size() + " zone classes and " + getSize() + " zones.");
    LOGGER.info(getClass().getSimpleName() + ": Loaded " + _spawnTerritories.size() + " NPC spawn territoriers.");
    final OptionalInt maxId = _classZones.values().stream().flatMap(map -> map.keySet().stream()).mapToInt(Integer.class::cast).filter(value -> value < 300000).max();
    LOGGER.info(getClass().getSimpleName() + ": Last static id: " + maxId.getAsInt());
}
项目:Java-EX    文件:JsonPrinter.java   
@SuppressWarnings("unchecked")
public JsonPrinter addJavaHandlers() {
  return this
      .addObjectClassHandler(Enum.class, e -> e.name())
      .addObjectClassHandler(Optional.class, o -> o.orElse(null))
      .addObjectClassHandler(OptionalInt.class, i -> i.isPresent() ? i.getAsInt() : null)
      .addObjectClassHandler(OptionalDouble.class, i -> i.isPresent() ? i.getAsDouble() : null)
      .addObjectClassHandler(OptionalLong.class, i -> i.isPresent() ? i.getAsLong() : null)
      .addObjectClassHandler(Class.class, c -> c.getName())
      .addObjectClassHandler(Path.class, p -> p.toString().replace('\\', '/'))
      .addObjectClassHandler(File.class, f -> f.toString().replace('\\', '/'));
}
项目:guava-mock    文件:StreamsTest.java   
public void testFindLast_intStream() {
  Truth.assertThat(findLast(IntStream.of())).isEqualTo(OptionalInt.empty());
  Truth.assertThat(findLast(IntStream.of(1, 2, 3, 4, 5))).isEqualTo(OptionalInt.of(5));

  // test with a large, not-subsized Spliterator
  List<Integer> list =
      IntStream.rangeClosed(0, 10000).boxed().collect(Collectors.toCollection(LinkedList::new));
  Truth.assertThat(findLast(list.stream().mapToInt(i -> i))).isEqualTo(OptionalInt.of(10000));

  // no way to find out the stream is empty without walking its spliterator
  Truth.assertThat(findLast(list.stream().mapToInt(i -> i).filter(i -> i < 0)))
      .isEqualTo(OptionalInt.empty());
}
项目:dropwizard-hikaricp-benchmark    文件:HikariDataSourceFactoryTest.java   
@Test
public void canDeserializeCorrectly() throws IOException, ConfigurationException {
    final HikariDataSourceFactory factory = new YamlConfigurationFactory<>(HikariDataSourceFactory.class,
            BaseValidator.newValidator(), Jackson.newObjectMapper(), "dw")
            .build(new ResourceConfigurationSourceProvider(), "config.yaml");

    assertThat(factory.getUser()).isEqualTo("nick");
    assertThat(factory.getPassword()).isEqualTo("nickss");
    assertThat(factory.getDatasourceClassName()).isEqualTo("org.postgresql.ds.PGSimpleDataSource");
    assertThat(factory.getProperties()).containsExactly(entry("databaseName", "postgres"));
    assertThat(factory.getMinSize()).isEqualTo(OptionalInt.empty());
    assertThat(factory.getMaxSize()).isEqualTo(12);
    assertThat(factory.isAutoCommit()).isTrue();
}
项目:scanning    文件:ExperimentConfiguration.java   
public int getLocalValueIndex(IQueueValue<?> value) throws QueueModelException {
    OptionalInt indexOpt = IntStream.range(0, localValues.size()).filter(i -> value.equals(localValues.get(i))).findFirst();
    try {
        return indexOpt.getAsInt();
    } catch (NoSuchElementException nseEx) {
        throw new QueueModelException(nseEx);
    }
}
项目:openjdk-jdk10    文件:ReaderTest.java   
private void verifyFrameStart(boolean fin,
                              boolean rsv1,
                              boolean rsv2,
                              boolean rsv3,
                              Opcode opcode,
                              long payloadLen,
                              OptionalInt mask) {
    frames++;
    Frame.HeaderWriter w = new Frame.HeaderWriter();
    ByteBuffer h = ByteBuffer.allocate(Frame.MAX_HEADER_SIZE_BYTES);
    w.fin(fin).rsv1(rsv1).rsv2(rsv2).rsv3(rsv3).opcode(opcode).payloadLen(payloadLen);
    mask.ifPresentOrElse(w::mask, w::noMask);
    w.write(h);
    h.flip();
    forEachBufferPartition(h,
            buffers -> {
                cases++;
                Frame.Reader r = new Frame.Reader();
                MockConsumer c = new MockConsumer();
                for (ByteBuffer b : buffers) {
                    r.readFrame(b, c);
                }
                assertEquals(fin, c.fin());
                assertEquals(rsv1, c.rsv1());
                assertEquals(rsv2, c.rsv2());
                assertEquals(rsv3, c.rsv3());
                assertEquals(opcode, c.opcode());
                assertEquals(mask.isPresent(), c.mask());
                assertEquals(payloadLen, c.payloadLen());
                assertEquals(mask, c.maskingKey());
                assertEquals(payloadLen == 0, c.isEndFrame());
            });
}
项目:beanmother    文件:JavaOptionalConverterModuleTest.java   
@Test
public void testNumberToOptionalLongConverter() {
    converter = new JavaOptionalConverterModule.NumberToOptionalLongConverter();

    assertTrue(converter.canHandle(1f, TypeToken.of(OptionalLong.class)));
    assertFalse(converter.canHandle(1f, TypeToken.of(OptionalInt.class)));

    Object result = converter.convert(1f, TypeToken.of(OptionalLong.class));
    assertTrue(result instanceof OptionalLong);
    assertEquals(1l, ((OptionalLong) result).getAsLong());
}
项目:uroborosql    文件:OptionalIntPropertyMapper.java   
@Override
public OptionalInt getValue(final JavaType type, final ResultSet rs, final int columnIndex,
        final PropertyMapperManager mapperManager) throws SQLException {
    int value = rs.getInt(columnIndex);
    if (!rs.wasNull()) {
        return OptionalInt.of(value);
    } else {
        return OptionalInt.empty();
    }
}
项目:openjdk-jdk10    文件:ReduceOps.java   
/**
 * Constructs a {@code TerminalOp} that implements a functional reduce on
 * {@code int} values, producing an optional integer result.
 *
 * @param operator the combining function
 * @return a {@code TerminalOp} implementing the reduction
 */
public static TerminalOp<Integer, OptionalInt>
makeInt(IntBinaryOperator operator) {
    Objects.requireNonNull(operator);
    class ReducingSink
            implements AccumulatingSink<Integer, OptionalInt, ReducingSink>, Sink.OfInt {
        private boolean empty;
        private int state;

        public void begin(long size) {
            empty = true;
            state = 0;
        }

        @Override
        public void accept(int t) {
            if (empty) {
                empty = false;
                state = t;
            }
            else {
                state = operator.applyAsInt(state, t);
            }
        }

        @Override
        public OptionalInt get() {
            return empty ? OptionalInt.empty() : OptionalInt.of(state);
        }

        @Override
        public void combine(ReducingSink other) {
            if (!other.empty)
                accept(other.state);
        }
    }
    return new ReduceOp<Integer, OptionalInt, ReducingSink>(StreamShape.INT_VALUE) {
        @Override
        public ReducingSink makeSink() {
            return new ReducingSink();
        }
    };
}
项目:OpenJSharp    文件:IntPipeline.java   
@Override
public final OptionalInt min() {
    return reduce(Math::min);
}
项目:amazon-kinesis-video-streams-parser-library    文件:StreamingMkvReader.java   
StreamingMkvReader(boolean requirePath,
        Collection<EBMLTypeInfo> typeInfosToRead,
        ParserByteSource byteSource) {
    this(requirePath, typeInfosToRead, byteSource, OptionalInt.empty());
}
项目:googles-monorepo-demo    文件:StreamsTest.java   
public void testStream_optionalInt() {
  assertThat(stream(java.util.OptionalInt.empty())).isEmpty();
  assertThat(stream(java.util.OptionalInt.of(5))).containsExactly(5);
}
项目:jdk8u-jdk    文件:FindOps.java   
@Override
public OptionalInt get() {
    return hasValue ? OptionalInt.of(value) : null;
}
项目:jdk8u-jdk    文件:BasicInt.java   
@Test(expectedExceptions=NoSuchElementException.class)
public void testEmptyGet() {
    OptionalInt empty = OptionalInt.empty();

    int got = empty.getAsInt();
}
项目:GitHub    文件:DefaultSpecializedOptionals.java   
@Value.Default
default OptionalInt value() {
  return OptionalInt.empty();
}
项目:GitHub    文件:UsingAllOptionals.java   
@Value.Parameter
OptionalInt i1();
项目:GitHub    文件:JdkOptionals.java   
@Value.Parameter
OptionalInt i1();
项目:GitHub    文件:JdkOptionalBuilderFactory.java   
@Builder.Factory
public static int appl(Optional<Integer> a, java.util.Optional<String> b, java.util.OptionalInt c) {
  return a.hashCode() + b.hashCode() + c.hashCode();
}
项目:GitHub    文件:JdkOptionalBuilderFactory.java   
@Builder.Factory
public static int bbz(@Builder.Parameter java.util.Optional<String> b, @Builder.Parameter java.util.OptionalInt c) {
  return b.hashCode() + c.hashCode();
}
项目:GitHub    文件:UseCompactOptionals.java   
@Value.Parameter
OptionalInt a();
项目:NioSmtpClient    文件:InputStreamMessageContent.java   
public InputStreamMessageContent(Supplier<InputStream> streamSupplier, OptionalInt size, MessageContentEncoding encoding) {
  this.streamSupplier = streamSupplier;
  this.size = size;
  this.encoding = encoding;
}
项目:openjdk-jdk10    文件:MinMaxTest.java   
public void testIntMinMax() {
    assertEquals(IntStream.empty().min(), OptionalInt.empty());
    assertEquals(IntStream.empty().max(), OptionalInt.empty());
    assertEquals(1, IntStream.range(1, 1001).min().getAsInt());
    assertEquals(1000, IntStream.range(1, 1001).max().getAsInt());
}
项目:NioSmtpClient    文件:ByteBufMessageContent.java   
@Override
public OptionalInt size() {
  return OptionalInt.of(size);
}
项目:stroom-stats    文件:CacheConfigurationServiceImpl.java   
private OptionalInt getPropertyValue(final String cacheName, final String propertySuffix) {
    return stroomPropertyService.getIntProperty(buildKey(cacheName, propertySuffix));
}
项目:stroom-stats    文件:Config.java   
public OptionalInt getAdvertisedPort() {
    return advertisedPort;
}
项目:Java-EE-8-Sampler    文件:OptionalIntExample.java   
public OptionalIntExample(Integer value) {
    this.value = OptionalInt.of(value);
}
项目:Java-EE-8-Sampler    文件:StandardTypeExampleTest.java   
@Test
public void givenIntegerJSON_shouldDeserialiseToOptionalInt() {
    assertThat(jsonb.fromJson("{\"value\":10}", OptionalIntExample.class))
            .hasFieldOrPropertyWithValue("value", OptionalInt.of(10));
}
项目:openjdk-jdk10    文件:IntPipeline.java   
@Override
public final OptionalInt findFirst() {
    return evaluate(FindOps.makeInt(true));
}