java.util.Optional.orElseThrow()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(9.3k)|赞(0)|评价(0)|浏览(152)

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

Optional.orElseThrow介绍

[英]Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.
[中]返回包含的值(如果存在),否则抛出由提供的供应商创建的异常。

代码示例

canonical example by Tabnine

private Double calculateAverageGrade(Map<String, List<Integer>> gradesList, String studentName)
  throws Exception {
 return Optional.ofNullable(gradesList.get(studentName))
   .map(list -> list.stream().collect(Collectors.averagingDouble(x -> x)))
   .orElseThrow(() -> new Exception("Student not found - " + studentName));
}

代码示例来源:origin: spring-projects/spring-framework

private static <T> HttpMessageWriter<T> findWriter(
    BodyInserter.Context context, ResolvableType elementType, @Nullable MediaType mediaType) {
  return context.messageWriters().stream()
      .filter(messageWriter -> messageWriter.canWrite(elementType, mediaType))
      .findFirst()
      .map(BodyInserters::<T>cast)
      .orElseThrow(() -> new IllegalStateException(
          "No HttpMessageWriter for \"" + mediaType + "\" and \"" + elementType + "\""));
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public RouterFunction<ServerResponse> build() {
  RouterFunction<ServerResponse> result = this.routerFunctions.stream()
      .reduce(RouterFunction::and)
      .orElseThrow(IllegalStateException::new);
  if (this.filterFunctions.isEmpty()) {
    return result;
  }
  else {
    HandlerFilterFunction<ServerResponse, ServerResponse> filter =
        this.filterFunctions.stream()
            .reduce(HandlerFilterFunction::andThen)
            .orElseThrow(IllegalStateException::new);
    return result.filter(filter);
  }
}

代码示例来源:origin: prestodb/presto

private <K, V> V loadValue(Cache<K, V> cache, K key, Supplier<V> valueSupplier)
{
  if (replay) {
    return Optional.ofNullable(cache.getIfPresent(key))
        .orElseThrow(() -> new PrestoException(NOT_FOUND, "Missing entry found for key: " + key));
  }
  V value = valueSupplier.get();
  cache.put(key, value);
  return value;
}

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

private static String findVersion(Map<Interval, String> versions, Interval interval)
{
 return versions.entrySet().stream()
         .filter(entry -> entry.getKey().contains(interval))
         .map(Entry::getValue)
         .findFirst()
         .orElseThrow(() -> new ISE("Cannot find a version for interval[%s]", interval));
}

代码示例来源:origin: hs-web/hsweb-framework

@GetMapping(value = "/md5/{md5}")
  @ApiOperation("根据MD5获取文件信息")
  public ResponseMessage<FileInfoEntity> uploadStatic(@PathVariable String md5) throws IOException {
    return ofNullable(fileInfoService.selectByMd5(md5))
        .map(ResponseMessage::ok)
        .orElseThrow(() -> new NotFoundException("file not found"));
  }
}

代码示例来源:origin: prestodb/presto

private void closeWorker()
    throws Exception
{
  int nodeCount = getNodeCount();
  DistributedQueryRunner queryRunner = (DistributedQueryRunner) getQueryRunner();
  TestingPrestoServer worker = queryRunner.getServers().stream()
      .filter(server -> !server.isCoordinator())
      .findAny()
      .orElseThrow(() -> new IllegalStateException("No worker nodes"));
  worker.close();
  waitForNodes(nodeCount - 1);
}

代码示例来源:origin: Graylog2/graylog2-server

private IndexSetConfig findDefaultIndexSet() {
  final List<IndexSetConfig> indexSetConfigs = indexSetService.findAll();
  // If there is more than one index set, we have a problem. Since there wasn't a way to create index sets
  // manually until now, this should not happen.
  checkState(indexSetConfigs.size() < 2, "Found more than one index set config!");
  // If there is no index set, a previous migration didn't work.
  return indexSetConfigs.stream()
      .findFirst()
      .orElseThrow(() -> new IllegalStateException("Couldn't find any index set config!"));
}

代码示例来源:origin: SonarSource/sonarqube

private static Project createProject(org.sonar.ce.task.CeTask ceTask) {
 return ceTask.getMainComponent()
  .map(c -> new ProjectImpl(
   c.getUuid(),
   c.getKey().orElseThrow(() -> new IllegalStateException("Missing project key")),
   c.getName().orElseThrow(() -> new IllegalStateException("Missing project name"))))
  .orElseThrow(() -> new IllegalStateException("Report processed for a task of a deleted component"));
}

代码示例来源:origin: google/error-prone

private ClassTree getTopLevelClass(VisitorState state) {
 return (ClassTree)
   Streams.findLast(
       Streams.stream(state.getPath().iterator())
         .filter((Tree t) -> t.getKind() == Kind.CLASS))
     .orElseThrow(() -> new IllegalArgumentException("No enclosing class found"));
}

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

@Test
void lookupFileByDatabaseFile()
{
  DatabaseLayout layout = testDirectory.databaseLayout();
  DatabaseFile[] databaseFiles = DatabaseFile.values();
  for ( DatabaseFile databaseFile : databaseFiles )
  {
    assertNotNull( layout.file( databaseFile ).findAny().orElseThrow( () -> new RuntimeException( "Mapping was expected to be found" ) ) );
  }
  File metadata = layout.file( DatabaseFile.METADATA_STORE ).findFirst().orElseThrow( () -> new RuntimeException( "Mapping was expected to be found" ) );
  assertEquals( "neostore", metadata.getName() );
}

代码示例来源:origin: spring-projects/spring-framework

private static <T> HttpMessageReader<T> findReader(
    ResolvableType elementType, MediaType mediaType, BodyExtractor.Context context) {
  return context.messageReaders().stream()
      .filter(messageReader -> messageReader.canRead(elementType, mediaType))
      .findFirst()
      .map(BodyExtractors::<T>cast)
      .orElseThrow(() -> new IllegalStateException(
          "No HttpMessageReader for \"" + mediaType + "\" and \"" + elementType + "\""));
}

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

private static String findVersion(Map<Interval, String> versions, Interval interval)
{
 return versions.entrySet().stream()
         .filter(entry -> entry.getKey().contains(interval))
         .map(Entry::getValue)
         .findFirst()
         .orElseThrow(() -> new ISE("Cannot find a version for interval[%s]", interval));
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Run the client, pulling credentials from the environment.
 * Throws an IllegalStateException if the required environment variables aren't set.
 * These are:
 *
 * <ul>
 *   <li>CORENLP_HOST</li>
 *   <li>CORENLP_KEY</li>
 *   <li>CORENLP_SECRET</li>
 * </ul>
 *
 * @throws IllegalStateException Thrown if we could not read the required environment variables.
 */
@SuppressWarnings("unused")
public StanfordCoreNLPClient(Properties properties) throws IllegalStateException {
 this(properties,
   Optional.ofNullable(System.getenv("CORENLP_HOST")).orElseThrow(() -> new IllegalStateException("Environment variable CORENLP_HOST not specified")),
   Optional.ofNullable(System.getenv("CORENLP_HOST")).map(x -> x.startsWith("http://") ? 80 : 443).orElse(443),
   1,
   Optional.ofNullable(System.getenv("CORENLP_KEY")).orElse(null),
   Optional.ofNullable(System.getenv("CORENLP_SECRET")).orElse(null)
  );
}

代码示例来源:origin: prestodb/presto

QualifiedObjectName tableName = createQualifiedObjectName(session, statement, statement.getTable());
TableHandle tableHandle = metadata.getTableHandle(session, tableName)
    .orElseThrow(() -> new SemanticException(MISSING_TABLE, statement, "Table '%s' does not exist", tableName));
if (metadata.getTableMetadata(session, tableHandle).getColumns().stream()
    .filter(info -> !info.isHidden()).count() <= 1) {
  throw new SemanticException(NOT_SUPPORTED, statement, "Cannot drop the only column in a table");

代码示例来源:origin: micronaut-projects/micronaut-core

/**
   * Resolve the current {@link Subscriber}.
   *
   * @return An {@link Optional} of the subscriber
   * @throws IllegalStateException If no {@link Subscriber} is present
   */
  protected Subscriber<? super T> getDownstreamSubscriber() {
    return Optional.ofNullable(this.downstreamSubscriber.get()).orElseThrow(() -> new IllegalStateException("No subscriber present!"));
  }
}

代码示例来源:origin: prestodb/presto

private String getPartitionName(String databaseName, String tableName, List<String> partitionValues)
{
  Table table = getTable(databaseName, tableName)
      .orElseThrow(() -> new TableNotFoundException(new SchemaTableName(databaseName, tableName)));
  List<String> columnNames = table.getPartitionColumns().stream()
      .map(Column::getName)
      .collect(toImmutableList());
  return makePartName(columnNames, partitionValues);
}

代码示例来源:origin: testcontainers/testcontainers-java

public VncRecordingContainer(@NonNull GenericContainer<?> targetContainer) {
  this(
      targetContainer.getNetwork(),
      targetContainer.getNetworkAliases().stream()
          .findFirst()
          .orElseThrow(() -> new IllegalStateException("Target container must have a network alias"))
  );
}

代码示例来源:origin: Graylog2/graylog2-server

@GET
@Path("{id}/stats")
@Timed
@ApiOperation(value = "Get index set statistics")
@ApiResponses(value = {
    @ApiResponse(code = 403, message = "Unauthorized"),
    @ApiResponse(code = 404, message = "Index set not found"),
})
public IndexSetStats indexSetStatistics(@ApiParam(name = "id", required = true)
                    @PathParam("id") String id) {
  checkPermission(RestPermissions.INDEXSETS_READ, id);
  return indexSetRegistry.get(id)
      .map(indexSetStatsCreator::getForIndexSet)
      .orElseThrow(() -> new NotFoundException("Couldn't load index set with ID <" + id + ">"));
}

代码示例来源:origin: google/error-prone

private static ClassTree getTopLevelClassTree(VisitorState state) {
 return (ClassTree)
   Streams.findLast(
       Streams.stream(state.getPath().iterator())
         .filter((Tree t) -> t.getKind() == Kind.CLASS))
     .orElseThrow(() -> new IllegalArgumentException("No enclosing class found"));
}

相关文章