com.google.common.base.Optional.get()方法的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(8.9k)|赞(0)|评价(0)|浏览(104)

本文整理了Java中com.google.common.base.Optional.get()方法的一些代码示例,展示了Optional.get()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Optional.get()方法的具体详情如下:
包路径:com.google.common.base.Optional
类名称:Optional
方法名:get

Optional.get介绍

[英]Returns the contained instance, which must be present. If the instance might be absent, use #or(Object) or #orNull instead.

Comparison to java.util.Optional: when the value is absent, this method throws IllegalStateException, whereas the Java 8 counterpart throws java.util.NoSuchElementException.
[中]返回包含的实例,该实例必须存在。如果实例可能不存在,请使用#or(Object)或#orNull。
与java的比较。util。可选:当值不存在时,此方法抛出IllegalStateException,而Java 8对应方抛出Java。util。没有什么例外。

代码示例

代码示例来源:origin: google/guava

/**
 * If a value is present in {@code optional}, returns a stream containing only that element,
 * otherwise returns an empty stream.
 */
public static <T> Stream<T> stream(com.google.common.base.Optional<T> optional) {
 return optional.isPresent() ? Stream.of(optional.get()) : Stream.of();
}

代码示例来源:origin: google/guava

@Override
public Optional<Long> sizeIfKnown() {
 Optional<Long> optionalUnslicedSize = ByteSource.this.sizeIfKnown();
 if (optionalUnslicedSize.isPresent()) {
  long unslicedSize = optionalUnslicedSize.get();
  long off = Math.min(offset, unslicedSize);
  return Optional.of(Math.min(length, unslicedSize - off));
 }
 return Optional.absent();
}

代码示例来源:origin: apache/incubator-shardingsphere

private static void changeColumnDefinitionPosition(final ColumnFirstPositionSegment columnFirstPositionSegment, final List<ColumnMetaData> columnMetaDataList) {
  Optional<ColumnMetaData> columnMetaData = find(columnFirstPositionSegment.getColumnName(), columnMetaDataList);
  if (columnMetaData.isPresent()) {
    columnMetaDataList.remove(columnMetaData.get());
    columnMetaDataList.add(0, columnMetaData.get());
  }
}

代码示例来源:origin: spotify/helios

private static List<Identity> getSshIdentities(final Optional<AgentProxy> agentProxyOpt) {
 // ssh identities (potentially) used in authentication
 final ImmutableList.Builder<Identity> listBuilder = ImmutableList.builder();
 if (agentProxyOpt.isPresent()) {
  try {
   final List<Identity> identities = agentProxyOpt.get().list();
   for (final Identity identity : identities) {
    if (identity.getPublicKey().getAlgorithm().equals("RSA")) {
     // only RSA keys will work with our TLS implementation
     listBuilder.add(identity);
    }
   }
  } catch (Exception e) {
   // We catch everything because right now the masters do not require authentication.
   // So delay reporting errors to the user until the servers return 401 Unauthorized.
   log.debug("Unable to get identities from ssh-agent. Note that this might not indicate"
        + " an actual problem unless your Helios cluster requires authentication"
        + " for all requests.", e);
  }
 }
 return listBuilder.build();
}

代码示例来源:origin: apache/incubator-gobblin

.setFields("files/id,files/mimeType,files/modifiedTime,files/size,files/permissions")
  .setPageSize(pageSize);
if (query.isPresent()) {
 request = request.setQ(query.get());
 LOG.debug("Google drive List request: " + request);

代码示例来源:origin: PipelineAI/pipeline

@Test
public void testGetMethodFoo(){
  Optional<Method> method =  MethodProvider.getInstance().getMethod(C.class, methodName, parametersTypes);
  assertTrue(method.isPresent());
  assertEquals(methodName, method.get().getName());
}

代码示例来源:origin: robolectric/robolectric

@Test
public void shouldSendSensorEventToMultipleRegisteredListeners() {
 TestSensorEventListener listener1 = new TestSensorEventListener();
 TestSensorEventListener listener2 = new TestSensorEventListener();
 Sensor sensor = sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
 sensorManager.registerListener(listener1, sensor, SensorManager.SENSOR_DELAY_NORMAL);
 sensorManager.registerListener(listener2, sensor, SensorManager.SENSOR_DELAY_NORMAL);
 SensorEvent event = shadow.createSensorEvent();
 shadow.sendSensorEventToListeners(event);
 assertThat(listener1.getLatestSensorEvent().get()).isEqualTo(event);
 assertThat(listener2.getLatestSensorEvent().get()).isEqualTo(event);
}

代码示例来源:origin: apache/flume

if (!kafkaFutures.isPresent()) {
 kafkaFutures = Optional.of(new LinkedList<Future<RecordMetadata>>());
 long batchSize = producerRecords.get().size();
 long startTime = System.nanoTime();
 int index = 0;
 for (ProducerRecord<String, byte[]> record : producerRecords.get()) {
  index++;
  kafkaFutures.get().add(producer.send(record, new ChannelCallback(index, startTime)));
 for (Future<RecordMetadata> future : kafkaFutures.get()) {
  future.get();
 counter.addToKafkaEventSendTimer((endTime - startTime) / (1000 * 1000));
 counter.addToEventPutSuccessCount(batchSize);
 producerRecords.get().clear();
 kafkaFutures.get().clear();
} catch (Exception ex) {
 logger.warn("Sending events to Kafka failed", ex);
 counter.addToKafkaCommitTimer((endTime - startTime) / (1000 * 1000));
 if (logger.isDebugEnabled()) {
  logger.debug(consumerAndRecords.get().getCommittedOffsetsString());
int takes = events.get().size();
if (takes > 0) {
 counter.addToEventTakeSuccessCount(takes);
 events.get().clear();

代码示例来源:origin: apache/usergrid

logger.debug("getApplications(): Loading edges of edgeType {} from {}:{}",
  edgeType, managementId.getType(), managementId.getUuid());
  Optional.<Edge>absent() ) );
        if ( !entity.getEntity().isPresent() ) {
          return;
          entity.getEntity().get();

代码示例来源:origin: dreamhead/moco

@Test
public void should_parse_without_port() {
  StartArgs args = startArgsParser.parse(new String[]{"start", "-c", "foo.json"});
  assertThat(args.getPort(), is(Optional.<Integer>absent()));
  assertThat(args.getConfigurationFile().get(), is("foo.json"));
}

代码示例来源:origin: jclouds/legacy-jclouds

public void testListWhenResponseIs404() throws Exception {
 HttpResponse listResponse = HttpResponse.builder().statusCode(404).build();
 EC2Api apiWhenDontExist = requestSendsResponse(
    list, listResponse);
 assertEquals(apiWhenDontExist.getTagApi().get().list().toSet(), ImmutableSet.of());
}

代码示例来源:origin: apache/incubator-gobblin

@Test(dependsOnMethods = "testSetupAndSubmitApplication")
public void testGetReconnectableApplicationId() throws Exception {
 // Assert to check if cluster was created correctly by trying to reconnect to it
 Assert.assertEquals(this.gobblinAwsClusterLauncher.getReconnectableClusterId().get(), this.clusterId);
}

代码示例来源:origin: apache/incubator-gobblin

@Test(dependsOnMethods = { "testPut" })
 public void testGet() throws IOException {
  Optional<CommitSequence> sequence2 = this.store.get(this.jobName, this.datasetUrn);
  Assert.assertTrue(sequence2.isPresent());
  Assert.assertEquals(GSON.toJsonTree(sequence2.get()), GSON.toJsonTree(this.sequence));
 }
}

代码示例来源:origin: google/guava

public void testGet_absent() {
 Optional<String> optional = Optional.absent();
 try {
  optional.get();
  fail();
 } catch (IllegalStateException expected) {
 }
}

代码示例来源:origin: google/guava

public void testOf() {
 assertEquals("training", Optional.of("training").get());
}

代码示例来源:origin: google/guava

@Override
public Optional<Long> lengthIfKnown() {
 long result = 0L;
 for (CharSource source : sources) {
  Optional<Long> lengthIfKnown = source.lengthIfKnown();
  if (!lengthIfKnown.isPresent()) {
   return Optional.absent();
  }
  result += lengthIfKnown.get();
 }
 return Optional.of(result);
}

代码示例来源:origin: apache/incubator-shardingsphere

private static void changeColumnDefinitionPosition(final ColumnAfterPositionSegment columnAfterPositionSegment, final List<ColumnMetaData> columnMetaDataList) {
  Optional<ColumnMetaData> columnMetaData = find(columnAfterPositionSegment.getColumnName(), columnMetaDataList);
  Optional<ColumnMetaData> afterColumnMetaData = find(columnAfterPositionSegment.getAfterColumnName(), columnMetaDataList);
  if (columnMetaData.isPresent() && afterColumnMetaData.isPresent()) {
    columnMetaDataList.remove(columnMetaData.get());
    columnMetaDataList.add(columnMetaDataList.indexOf(afterColumnMetaData.get()) + 1, columnMetaData.get());
  }
}

代码示例来源:origin: twitter/distributedlog

void moveRemainingStreamsFromSource(Host source,
                  List<Host> hosts,
                  Optional<RateLimiter> rateLimiter) {
  LinkedList<String> streamsToMove = new LinkedList<String>(source.streams);
  Collections.shuffle(streamsToMove);
  if (logger.isDebugEnabled()) {
    logger.debug("Try to move remaining streams from {} : {}", source, streamsToMove);
  }
  int hostIdx = hosts.size() - 1;
  while (!streamsToMove.isEmpty()) {
    if (rateLimiter.isPresent()) {
      rateLimiter.get().acquire();
    }
    Host target = hosts.get(hostIdx);
    if (!target.address.equals(source.address)) {
      String stream = streamsToMove.remove();
      // move the stream
      if (moveStream(stream, source, target)) {
        source.streams.remove(stream);
        target.streams.add(stream);
      }
    }
    --hostIdx;
    if (hostIdx < 0) {
      hostIdx = hosts.size() - 1;
    }
  }
}

代码示例来源:origin: twitter/distributedlog

@Test(timeout = 60000)
public void testGetLogLocation() throws Exception {
  Optional<URI> uriOptional = FutureUtils.result(metadataStore.getLogLocation("test"));
  assertTrue(uriOptional.isPresent());
  assertEquals(uri, uriOptional.get());
}

代码示例来源:origin: dreamhead/moco

@Test
public void should_parse_settings() {
  StartArgs args = startArgsParser.parse(new String[]{"start", "-p", "12306", "-g", "settings.json"});
  assertThat(args.getSettings().get(), is("settings.json"));
}

相关文章