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)); }
@Override public Optional<Customer> getById(final int id) { return Optional.ofNullable(idToCustomer.get(id)); }
/** * Determine a media type for the given resource, if possible. * @param resource the resource to introspect * @return the corresponding media type, or {@code null} if none found */ public static Optional<MediaType> getMediaType(@Nullable Resource resource) { return Optional.ofNullable(resource) .map(Resource::getFilename) .flatMap(MediaTypeFactory::getMediaType); }
@Override @JsonProperty public Optional<Duration> getValidationQueryTimeout() { return Optional.ofNullable(validationQueryTimeout); }
@Override public void configure(Map<String, String> options) { useCache = Optional.ofNullable(options.get("cache")).map(Boolean::parseBoolean).orElse(true); fileRoot = Optional.ofNullable(options.get("fileRoot")).map(File::new); }
/** * Gets the list of <em>instances</em> associated to a virtual host name. * * @param virtualHostName * the virtual hostname for which the instances need to be * returned. * @return list of <em>instances</em>. */ public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) { return Optional.ofNullable(this.virtualHostNameAppMap.get(virtualHostName.toUpperCase(Locale.ROOT))) .map(VipIndexSupport::getVipList) .map(AtomicReference::get) .orElseGet(Collections::emptyList); }
private Optional<String> parseTag(ProcessType requestType, LogLevel logLevel) { switch (requestType) { case FETCH: return Optional.ofNullable(FETCH_ARTIFACT_LOG_LEVEL_TAG.get(logLevel)); case PUBLISH: return Optional.ofNullable(PUBLISH_ARTIFACT_LOG_LEVEL_TAG.get(logLevel)); } return Optional.empty(); }
public Optional<String> getStringConfig(String name) { return config == null ? Optional.empty() : Optional.ofNullable(config.get(name)) .map(String::valueOf); } }
Optional<PartitionInfo> getPartitionInfo(TopicPartition topicPartition) { return Optional.ofNullable(metadataByPartition.get(topicPartition)) .map(PartitionInfoAndEpoch::partitionInfo); }
public List<GroupingOperation> getGroupingOperations(QuerySpecification querySpecification) { return Optional.ofNullable(groupingOperations.get(NodeRef.of(querySpecification))) .orElse(emptyList()); }
/** * Determine the media types for the given file name, if possible. * @param filename the file name plus extension * @return the corresponding media types, or an empty list if none found */ public static List<MediaType> getMediaTypes(@Nullable String filename) { return Optional.ofNullable(StringUtils.getFilenameExtension(filename)) .map(s -> s.toLowerCase(Locale.ENGLISH)) .map(fileExtensionToMediaTypes::get) .orElse(Collections.emptyList()); }
public <R> Optional<R> map(Function<? super T, ? extends R> mapper) { if (value == null) { return Optional.empty(); } else { return Optional.ofNullable(mapper.apply(value)); } }
@Override public OptionalDouble getValueFromAggregationQueryResult(Object value) { return Optional.ofNullable(value) .map(Number.class::cast) .map(Number::doubleValue) .map(OptionalDouble::of) .orElseGet(OptionalDouble::empty); }
private static <T, S extends Publisher<T>> S readWithMessageReaders( ReactiveHttpInputMessage message, BodyExtractor.Context context, ResolvableType elementType, Function<HttpMessageReader<T>, S> readerFunction, Function<UnsupportedMediaTypeException, S> errorFunction, Supplier<S> emptySupplier) { if (VOID_TYPE.equals(elementType)) { return emptySupplier.get(); } MediaType contentType = Optional.ofNullable(message.getHeaders().getContentType()) .orElse(MediaType.APPLICATION_OCTET_STREAM); return context.messageReaders().stream() .filter(reader -> reader.canRead(elementType, contentType)) .findFirst() .map(BodyExtractors::<T>cast) .map(readerFunction) .orElseGet(() -> { List<MediaType> mediaTypes = context.messageReaders().stream() .flatMap(reader -> reader.getReadableMediaTypes().stream()) .collect(Collectors.toList()); return errorFunction.apply( new UnsupportedMediaTypeException(contentType, mediaTypes, elementType)); }); }
private Optional<QueryFailureInfo> createQueryFailureInfo(ExecutionFailureInfo failureInfo, Optional<StageInfo> outputStage) { if (failureInfo == null) { return Optional.empty(); } Optional<TaskInfo> failedTask = outputStage.flatMap(QueryMonitor::findFailedTask); return Optional.of(new QueryFailureInfo( failureInfo.getErrorCode(), Optional.ofNullable(failureInfo.getType()), Optional.ofNullable(failureInfo.getMessage()), failedTask.map(task -> task.getTaskStatus().getTaskId().toString()), failedTask.map(task -> task.getTaskStatus().getSelf().getHost()), executionFailureInfoCodec.toJson(failureInfo))); }
private String getNameForReturnValue(MethodParameter returnType) { return Optional.ofNullable(returnType.getMethodAnnotation(ModelAttribute.class)) .filter(ann -> StringUtils.hasText(ann.value())) .map(ModelAttribute::value) .orElseGet(() -> Conventions.getVariableNameForParameter(returnType)); }
public static String fromResource(AbstractFileResolvingResource resource) { String filename = Optional.ofNullable(resource.getFilename()).orElse(""); return getMimeType(filename); }
private RuleUpdate createRuleUpdate(DbSession dbSession, RuleKey key, OrganizationDto organization) { RuleDto rule = dbClient.ruleDao().selectByKey(dbSession, organization, key) .orElseThrow(() -> new NotFoundException(format("This rule does not exist: %s", key))); RuleUpdate ruleUpdate = ofNullable(rule.getTemplateId()) .map(x -> RuleUpdate.createForCustomRule(key)) .orElseGet(() -> RuleUpdate.createForPluginRule(key)); ruleUpdate.setOrganization(organization); return ruleUpdate; }
/** * Gets the list of instances associated with this particular application. * <p> * Note that the instances are always returned with random order after * shuffling to avoid traffic to the same instances during startup. The * shuffling always happens once after every fetch cycle as specified in * {@link EurekaClientConfig#getRegistryFetchIntervalSeconds}. * </p> * * @return the list of shuffled instances associated with this application. */ @JsonProperty("instance") public List<InstanceInfo> getInstances() { return Optional.ofNullable(shuffledInstances.get()).orElseGet(this::getInstancesAsIsFromEureka); }
private static void makeRemovable(@Nonnull Path path) throws IOException { if (!Files.isWritable(path)) { makeWritable(path); } /* on Unix both the file and the directory that contains it has to be writable for a file deletion to be successful. (Confirmed on Solaris 9) $ ls -la total 6 dr-xr-sr-x 2 hudson hudson 512 Apr 18 14:41 . dr-xr-sr-x 3 hudson hudson 512 Apr 17 19:36 .. -r--r--r-- 1 hudson hudson 469 Apr 17 19:36 manager.xml -rw-r--r-- 1 hudson hudson 0 Apr 18 14:41 x $ rm x rm: x not removed: Permission denied */ Optional<Path> maybeParent = Optional.ofNullable(path.getParent()).map(Path::normalize).filter(p -> !Files.isWritable(p)); if (maybeParent.isPresent()) { makeWritable(maybeParent.get()); } }